在Ruby中搜索元音

时间:2014-07-18 23:13:10

标签: 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

6 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:3)

使用scan

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

答案 2 :(得分:3)

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

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

答案 3 :(得分:1)

无需:

str.chars.to_a

实际上,str.chars已经是一个数组

> String.new.chars.class
 => Array 

重构一点

str.chars.each{|i| i =~ /[aeiou]/ ? x : nil}
x.length

但是也许最佳解决方案的替代方法可能是:

a.chars.map{|x| x if x.match(/[aeiouAEIOU]/)}.join.size

您应该检查map块,因为您可以在内部执行一些有用的操作,以替代count块。

毫无疑问,使用块计算字符串内部元音的最佳解决方案:

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

答案 4 :(得分:0)

有更短的化身。

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

答案 5 :(得分:0)

以下是使用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