Reputation: 41
I have a hash of data that is holding different strings as its Key. I need to create a new method in my class that will count the number of vowels in each key and then return the key with the most vowels. I am very stuck and this is what I have so far.
def favorite_wish
vowels = ["a", "e", "i", "o", "u"]
@submitted_wishes.each_key do |wish|
wish.split(' ')
wish.each do |check|
if check == vowels
end
end
end
Can anyone help?
Upvotes: 0
Views: 127
Reputation: 106932
String#count
might help you:
# this will return the key with the max number of vowels
def favorite_wish
@submitted_wishes.keys.max_by { |wish| wish.count('aeiou') }
end
# this will return the value to the key with the max number of vowels
def favorite_wish
max_key = @submitted_wishes.keys.max_by { |wish| wish.count('aeiou') }
@submitted_wishes[max_key]
end
Upvotes: 1
Reputation: 110685
h = { "Mary"=>"Mary", "quite"=>"contrary", "how"=>"does your", "garden"=>"grow?" }
h.map { |k,_| [k.count('aeiou'), k] }.max.last
#=> => "quite"
The steps:
a = h.map { |k,_| [k.count('aeiou'), k] }
#=> [[1, "Mary"], [3, "quite"], [1, "how"], [2, "garden"]]
b = a.max
#=> [3, "quite"]
b.last
#=> "quite"
See Array#<=> for an explanation of how arrays are ordered (when computing max
).
If keys k1
and k2
tie for the maximum number of vowels, k1 <=> k2
breaks the tie (k1
is returned if k1 <=> k2 #=> -1
, k2
is returned if k1 <=> k2 #=> 1
, either key might be returned if k1 <=> k2 #=> 0
. See String#<=>.
Upvotes: 0
Reputation: 14584
I would use the following methods:
def count_vowels(str)
str.count 'aeiou'
end
def highest_value_key(hash)
hash.key(hash.values.max)
end
The idea behind these methods is to separate concerns and make it more readable.
Upvotes: 0
Reputation: 7956
This will get the key with the most vowels:
@submitted_wishes.keys.max_by { |key| key.count('aeiou') }
Upvotes: 0