4

I'd like to ask why having a splat param1 and a param2 with default value assignment in Ruby-1.9.3-p0 as below:

def my_method(*param1, param2 = "default"); end

returns

SyntaxError: (irb):1: syntax error, unexpected '=', expecting ')'

My workaround is explicitly wrap param1 in brackets like this:

def my_method((*param1), param2 = "default"); end

Many thanks

Trung Lê
  • 5,188
  • 5
  • 27
  • 26

1 Answers1

7

Ruby can't parse a parameter with a default after a splat. If you have default assignment in a parameter after a splat, how would Ruby know what to assign the variable to?

def my_method(*a, b = "foo"); end

Let's say I then call my_method:

my_method(1, 2, 3)

Ruby has no way of knowing whether b is missing, in which case you want b to be foo and a is [1,2,3], or if b is present in which case you want it to be 3.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Marc Talbot
  • 2,059
  • 2
  • 21
  • 27