2016-10-28 39 views
0

我有一个数据散列,它将不同的字符串作为它的键。我需要在我的课程中创建一个新方法,该方法将计算每个键中的元音数,然后返回具有最多元音的键。我很困难,这是我迄今为止所做的。写一个方法来检查字符串中的元音数

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 

任何人都可以帮忙吗?

回答

1

String#count可以帮助你:

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

我相信关键是要退货。 –

0

这将让最元音的关键是:

@submitted_wishes.keys.max_by { |key| key.count('aeiou') } 
0

我会用下面的方法:

def count_vowels(str) 
    str.count 'aeiou' 
end 

def highest_value_key(hash) 
    hash.key(hash.values.max) 
end 

背后的想法这些方法是分离关注点并使其更具可读性。

0
h = { "Mary"=>"Mary", "quite"=>"contrary", "how"=>"does your", "garden"=>"grow?" } 

h.map { |k,_| [k.count('aeiou'), k] }.max.last 
    #=> => "quite" 

的步骤:

a = h.map { |k,_| [k.count('aeiou'), k] } 
    #=> [[1, "Mary"], [3, "quite"], [1, "how"], [2, "garden"]] 
b = a.max 
    #=> [3, "quite"] 
b.last 
    #=> "quite" 

为阵列如何排序(计算max时)的说明见Array#<=>

如果键​​和k2并列元音的最大数量,k1 <=> k2打破返回领带(​​如果k1 <=> k2 #=> -1k2是,如果k1 <=> k2 #=> 1返回,要么密钥可能如果k1 <=> k2 #=> 0被退回。见String#<=>

相关问题