简体   繁体   中英

Ruby - Iterating over String that iterates over array

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

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.

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) }
}

Example

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM