map函数返回数字0或1的真或假

时间:2016-03-26 12:56:28

标签: arrays ruby dictionary

我试图通过将字符串拆分成字母数组然后将元音字母映射到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?部分无法正确返回10。有什么建议为什么这不会飞?

我把它破解到这个有效的版本,但看起来有点愚蠢:

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

3 个答案:

答案 0 :(得分:6)

原因:

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

答案 1 :(得分:1)

您不需要map

def count_vowels(string)
  vowels = %w[a e i o u]
  string.chars.select{|n| vowels.include? n}.size
end

答案 2 :(得分:0)

在这种情况下,您需要R方法参数的parantheses。所以

include?

无论如何,你的代码可能会更好

  • return string.split("").map{ |n| vowels.include?(n) }.inject(0) do |mem,x|
  • 你的方法不需要返回,这是最后一个声明
  • VOWELS = %w(a e i o u) # string's array => string.split("")

请注意,您的方法可能如此:

string.chars
相关问题