2016-10-28 4 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 당신을 도울 수 있습니다 뒤에

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

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

아이디어 :

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

저는 믿습니다 열쇠가 반환됩니다. –

0

이 가장 모음에 열쇠를 얻을 것이다 이러한 방법은 관심사를 분리하고 더 쉽게 읽을 수있게 만드는 것입니다.

0

나는 다음과 같은 방법을 사용합니다 :

# 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
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#<=>를 참조하십시오.

k1와 넥타이 (k1k1 <=> k2 #=> -1 경우, k1 <=> k2 #=> 1 경우 k2가 리턴됩니다 중 키가 k1 <=> k2 #=> 0 경우 리턴 될 수 반환 나누기 k1 <=> k2 모음의 최대 수에 대한 k2 넥타이. String#<=>를 참조하십시오.

관련 문제