Why Non-Explicit Splat Param Plus Default Param Is Wrong Syntax for Method Definition in Ruby 1.9

Why non-explicit splat param plus default param is wrong syntax for method definition in Ruby 1.9?

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.

How to set a default value for a splat argument in Ruby

Your attempted usage is counter the conventions around splat usage. Splats are supposed (at least in Ruby) to take up all extra (0, 1 or more) values.

If you know that you want the second value in your method arguments list to have a default value, you could take it out of the splat and list it just before the splat with a default value like this:

def a b, c=nil, *d 
# rest of code omitted
end

EDIT:
To make the answer to your question of why it doesn't work perfectly clear. It's a design decision by the language designer. Matz never intended the splat operator to work with defaults. This seems pretty sensible to me since it is intended to be used for catching an indeterminate number of variables and because the method I described reads more clearly than the possibilities you described and because all of the problems your examples solve are solvable in other ways.

Why is this splat method call not working in Ruby?

Default parameters (b) should come after positional parameters (a, c):

def method(a, c, b='a', *d)
[a,b,c, d]
end


Related Topics



Leave a reply



Submit