2016-08-27 6 views

答えて

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 
+0

' Enumerable#max_by'メソッドを見てください。 –

+0

ネクタイがあればどうなりますか? –

+0

@ sagarpandya82最初の発生が返されます –

2

Enumerable#max_byString#countを使用することをおすすめします。 MichałMłoźniakの答えとあなたが使用することができます@MladenJablanovićの提案@使用

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 
+0

OPはハッシュを検索するメソッドを要求しますか? –

+0

@ sagarpandya82、whoops!一定。ありがとう。 –

関連する問題