splat 参数后的可选参数 [英] Optional argument after splat argument
问题描述
这是我的程序:
def calculate(*numbers, options = {})
add(numbers) if options[:add]
subtract(numbers) if options[:add] == false
end
def add(*numbers)
numbers.reduce(:+)
end
def subtract(*numbers)
numbers.reduce(:-)
end
p calculate(1,2)
在第 1 行,它在抱怨
On line 1, it is complaining
tests.rb:1: 语法错误,意外的'=',期待')'
def计算(*数字,选项= {})
________________________________________________^
[0.1s 内完成,退出代码为 1]
tests.rb:1: syntax error, unexpected '=', expecting ')'
def calculate(*numbers, options = {})
________________________________________________^
[Finished in 0.1s with exit code 1]
我认为这可能是 Ruby 中默认值的问题,因为在 v1.9 之前,您需要按顺序拥有所有默认值 - 但这不应该是问题,因为我的版本是
I thought it might have been a problem with default values in Ruby, because before v1.9, you were required to have all default values in order - but this shouldn't be the issue because my version is
ruby 2.0.0p195 (2013-05-14) [i386-mingw32]
我试过把所有的空格都调换,因为 ruby 在方法方面似乎特别擅长那些东西,但没有骰子.
I've tried transposing the spaces all over, because ruby seems to be particular with those things when it comes to methods, but no dice.
可能是我的 splat 变量 *numbers
吗?
Could it be my splat variable *numbers
?
推荐答案
感谢 @maerics 和 @JorgWMittag -
Thanks @maerics and @JorgWMittag -
当你有一个 splat 时,它会保留所有参数,这就是为什么它不喜欢我的第二个选项"参数.我通过将我的参数更改为 -
When you have a splat, it reserves all arguments, which is why it was not liking my second "options" argument. I fixed this issue by changing my arguments around to -
def calculate(*arguments)
options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
options[:add] = true if options.empty?
return add(*arguments) if options[:add]
return subtract(*arguments) if options[:subtract]
end
这篇关于splat 参数后的可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!