Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional argument after splat argument

Tags:

ruby

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 ?

like image 871
ddavison Avatar asked Jun 18 '13 15:06

ddavison


People also ask

How do you indicate an optional argument?

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.

What is optional argument?

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.

What is optional arguments in VB?

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.

What is splat in Ruby?

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.


1 Answers

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"?

like image 139
maerics Avatar answered Oct 26 '22 09:10

maerics