我试图通过将字符串拆分为字母数组,然后将元音字母映射到1
并求和该数组来计算字符串中的元音数量。
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
return string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+)
end
该include?
部分不正确返回1
或0
。有什么建议为什么它不会飞吗?
我将其修改为可以正常工作的该版本,但看起来有点愚蠢:
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
return string.split("").map{ |n| vowels.include? n}.inject(0) do |mem,x|
x ? mem + 1 : mem
end
end
原因:
string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+)
之所以不起作用,是因为它n ? 1 : 0
被求值并作为参数传递给include?
而不是n
。您需要在中添加一些括号include?
:
string.split("").map{ |n| vowels.include?(n) ? 1 : 0}.inject(0,:+)
你可以简单地做
def count_vowels(string)
vowels = ['a','e', 'i', 'o', 'u']
string.split(//).select { |x| vowels.include? x }.length
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句