Reputation: 15
I want to count vowels in Ruby. The code I have come up with, and it works for one word is:
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
My question is this: If I have a list of words, rather than a single one, how do I iterate over the list of words to count the vowels in each word? Would it be something like this?
for each string_in list count_vowels
Upvotes: 0
Views: 159
Reputation: 44581
You can use .count
:
string.downcase.count('aeiou')
If you have a list of words, you can do the following:
def count_vowels(string)
string.downcase.count('aeiou')
end
list_of_words.map { |word|
{ word => count_vowels(word) }
}
Upvotes: 0
Reputation:
This is fairly simple. If you have the list of words as an array, you can just do this:
vowel_count = 0;
words.each { |word| vowel_count += count_vowels word }
Now, vowel_count
has the amount of vowels in every word.
You could also do something like this, if you want an array of each count of vowels:
vowel_counts = words.map { |word| count_vowels word }
Upvotes: 0
Reputation: 29870
First of all, to count vowels it's as easy as using the count
method:
string.downcase.count('aeiou')
If you have an array of strings, you can use each
to iterate over them. You can also use map
, which iterates over the collection and maps each result to an array.
['abc', 'def'].map do |string|
{ string => string.downcase.count('aeiou') }
end
This will return an array of hashes, with the keys being the strings and the values being the number of vowels.
Upvotes: 2