0

我正在尝试编写一个方法,该方法根据传递给它的关键字参数calculate确定 toadd或numbers。subtract

以下是方法:

def add(*num)
  num.inject(:+)
end

def subtract(*num)
  num.reduce(:-)
end

def calculate(*num, **op)
  return add(num) if op[:add] || op.empty?
  return subtract(num) if op[:subtract]
end

puts calculate(1, 2, 3, add: true)
puts calculate(1, 2, 3, subtract: true)

当我运行这个函数时,我得到这个结果:

1
2
3

1
2
3
4

2 回答 2

2

puts是你的朋友:

def add(*num)
  puts "in add, num = #{num}, num.size = #{num.size}"
  num.inject(:+)
end

def calculate(*num, **op)
  puts "num = #{num}, op = #{op}"
  return add(num) if op[:add] || op.empty?
end

calculate(1, 2, 3, add: true)
  # num = [1, 2, 3], op = {:add=>true}
  # in add, num = [[1, 2, 3]], num.size = 1
  #=> nil

现在修复calculate

def calculate(*num, **op)
  puts "num = #{num}, op = #{op}"
  return add(*num) if op[:add] || op.empty?
end

calculate(1, 2, 3, add: true)
  # num = [1, 2, 3], op = {:add=>true}
  # in add, num = [1, 2, 3], num.size = 3
  # => 6 
于 2015-02-21T21:01:16.097 回答
0

你写 :

return add(*num) if opt[:add] || opt.empty?

同样的方式修改返回减法..也是部分。

随着您发布的代码 num 变为 [[1,2,3]],因此 [[1,2,3]].inject(:+) 将接收器返回。你在它上面调用了 puts,所以它的输出就像你得到的一样。

于 2015-02-21T20:16:20.227 回答