简体   繁体   English

Ruby-在字符串上迭代在数组上迭代

[英]Ruby - Iterating over String that iterates over array

I want to count vowels in Ruby. 我想在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: 首先,对元音进行计数与使用count方法一样简单:

string.downcase.count('aeiou')

If you have an array of strings, you can use each to iterate over them. 如果您有一个字符串数组,则可以使用each字符串进行迭代。 You can also use map , which iterates over the collection and maps each result to an array. 您还可以使用map ,它遍历集合并将每个结果映射到一个数组。

['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 : 您可以使用.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. 现在, vowel_count具有每个单词中的元音数量。

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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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