ruby - Finding the most occurring character/letter in a string -
trying occurring letter in string.
so far:
puts "give me string" words = gets.chomp.split counts = hash.new(0) words.each |word| counts[word] += 1 end
does not run further asking string. doing wrong?
rather getting count word word, can process whole string immediately.
str = gets.chomp hash = hash.new(0) str.each_char |c| hash[c] += 1 unless c == " " #used filter space end
after getting number of letters, can find letter highest count with
max = hash.values.max
then match key in hash , you're done :)
puts hash.select{ |key| hash[key] == max }
or simplify above methods
hash.max_by{ |key,value| value }
the compact form of :
hash = hash.new(0) gets.chomp.each_char { |c| hash[c] += 1 unless c == " " } puts hash.max_by{ |key,value| value }
Comments
Post a Comment