[英]Ruby - Iterating over String that iterates over array
我想在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 vowel
end
我的問題是:如果我有一個單詞列表 ,而不是一個單詞列表 ,如何遍歷單詞列表以計算每個單詞中的元音? 會是這樣嗎?
for each string_in list count_vowels
首先,對元音進行計數與使用count
方法一樣簡單:
string.downcase.count('aeiou')
如果您有一個字符串數組,則可以使用each
字符串進行迭代。 您還可以使用map
,它遍歷集合並將每個結果映射到一個數組。
['abc', 'def'].map do |string|
{ string => string.downcase.count('aeiou') }
end
這將返回一個散列數組,鍵為字符串,值為元音數。
這很簡單。 如果您將單詞列表作為數組,則可以執行以下操作:
vowel_count = 0;
words.each { |word| vowel_count += count_vowels word }
現在, vowel_count
具有每個單詞中的元音數量。
如果想要每個元音數量的數組,也可以執行以下操作:
vowel_counts = words.map { |word| count_vowels word }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.