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
?
To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.
Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.
Optional parameters are indicated by the Optional keyword in the procedure definition. The following rules apply: Every optional parameter in the procedure definition must specify a default value. The default value for an optional parameter must be a constant expression.
Splat operator or start (*) arguments in Ruby define they way they are received to a variable. Single splat operator can be used to receive arguments as an array to a variable or destructure an array into arguments. Double splat operator can be used to destructure a hash.
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"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With