所以,假设我有一个充满字符串的哈希作为值。我如何创建一个方法来搜索哈希并返回其中元音最多的字符串?
答案 0 :(得分:2)
我建议您使用Enumerable#max_by和String#count。
def most_vowel_laden(h)
h.values.max_by { |str| str.count('aeiouAEIOU') }
end
keys = [1, 2, 3, 4, 5, 6]
h = keys.zip(%w| It was the best of times |).to_h
#=> {1=>"it", 2=>"was", 3=>"the", 4=>"best", 5=>"of", 6=>"times"}
most_vowel_laden h
#=> "times"
h = keys.zip(%w| by my dry fly why supercalifragilisticexpialidocious |).to_h
#=> {1=>"by", 2=>"my", 3=>"dry", 4=>"fly", 5=>"why",
# 6=>"supercalifragilisticexpialidocious"}
most_vowel_laden h
#=> "supercalifragilisticexpialidocious"
可替换地,
def most_vowel_laden(h)
h.max_by { |_,str| str.count('aeiouAEIOU') }.last
end
答案 1 :(得分:1)
result = nil
max = 0
# hash is your hash with strings
hash.values.each do |value|
vowels = value.scan(/[aeiouy]/).size
if vowels > max
max = vowels
result = value
end
end
puts result