Ruby-迭代数组的字符串
我想计算Ruby中的元音。我提出的代码,它适用于一个词:Ruby-迭代数组的字符串,ruby,Ruby,我想计算Ruby中的元音。我提出的代码,它适用于一个词: def count_vowels(string) vowel = 0 i = 0 while i < string.length if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u") vowel +=1 end i +=1 end return vowe
def count_vowels(string)
vowel = 0
i = 0
while i < string.length
if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
vowel +=1
end
i +=1
end
return vowel
end
您可以使用:
如果有单词列表,可以执行以下操作:
def count_vowels(string)
string.downcase.count('aeiou')
end
list_of_words.map { |word|
{ word => count_vowels(word) }
}
首先,要计算元音,与使用
count
方法一样简单:
string.downcase.count('aeiou')
如果您有一个字符串数组,可以使用每个
对其进行迭代。您还可以使用map
,它迭代集合并将每个结果映射到一个数组
['abc', 'def'].map do |string|
{ string => string.downcase.count('aeiou') }
end
这将返回一个哈希数组,其中键是字符串,值是元音数。这相当简单。如果将单词列表作为数组,则可以执行以下操作:
vowel_count = 0;
words.each { |word| vowel_count += count_vowels word }
现在,voral\u count
有了每个单词中的元音数量
如果您想要每个元音计数的数组,您也可以这样做:
vowel_counts = words.map { |word| count_vowels word }
我想你有一个额外的括号或缺少的括号。你想要元音的总计数还是计数的数组?我想要数组右边每个单词的元音计数。除非你真的想使用你的函数,否则最上面的答案应该可以帮你。这会给出所有单词元音的总数,而不是每个单独的单词
vowel_count = 0;
words.each { |word| vowel_count += count_vowels word }
vowel_counts = words.map { |word| count_vowels word }