Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

ruby - Optional argument after splat argument

Here is my program:

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)

On line 1, it is complaining

tests.rb:1: syntax error, unexpected '=', expecting ')'
def calculate(*numbers, options = {})
________________________________________________^
[Finished in 0.1s with exit code 1]

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]

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.

Could it be my splat variable *numbers ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot have optional parameters after a splat.

The splat means "use up all of the remaining arguments" but then you provide an optional argument, so how could the interpreter know if the last argument is part of the "numbers" splat or the optional "options"?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...