This article uses Ruby 2.6.3 installed on macOS.
I made a note of how to solve the Ruby super-introduction exercise (p154) that can be understood from scratch. I realized that I need to use hashes well for those that have a one-to-one correspondence.
Q: Please count the alphabets used in the string "caffe latte" and the number of times.
hash = {}
hash.default = 0
#Arrange each character in an array and sort them in alphabetical order
array = "caffelatte".chars.sort
#Character key,Create a hash with the number of times as the value
array.each { |x| hash[x] += 1}
#Shows how many times the character was used at the end
hash.each { |letter, count| puts "#{letter}Is#{count}Used times"}
Recommended Posts