在Ruby中搜索元音

str = "Find the vowels in this string or else I'll date your sister" 

我想要计算字符串中的元音数量,我相信我已经实现了这一点,但我已经通过将每个字母附加到数组并获取数组的长度来完成它。 有什么更常见的方式来做到这一点。 也许用+ =?

 str.chars.to_a.each do |i| if i =~ /[aeiou]/ x.push(i) end end x.length 

如果你想计算元音,为什么不使用count

 str.chars.count {|c| c =~ /[aeiou]/i } 

但这里有更好的答案=)。 事实certificate我们有一个String#count方法:

 str.downcase.count 'aeiou' #=> 17 

使用scan

 "Find the vowels in this string or else I'll date your sister".scan(/[aeiou]/i).length 

有更短的化身。

 $ irb >> "Find the vowels in this string or else I'll date your sister".gsub(/[^aeiou]/i, '').length => 17 

这是一种使用String#tr的方法 :

 str = "Find the vowels in this string or else I'll date your sister" str.size - str.tr('aeiouAEIOU','').size #=> 17 

要么

 str.size - str.downcase.tr('aeiou','').size #=> 17