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
Can Anyone Explain This Array Declaration to Me
Ternary Expression with "Defined" Returns "Expression" Instead of Value
Why Does Ruby Use Its Own Syntax for Safe Navigation Operator
What Does "File.Sync = True" Do
Why Does Single '=' Work in 'If' Statement
Rails 3: Belongs_To, Has_One and Migrations
Ruby Block Taking Array or Multiple Parameters
Dangerousattributeerror in Omniauth Railscast Tutorial: Create Is Defined by Activerecord
Accessing a Ruby Hash with a Variable as the Key
Gmaps4Rails:Setting Map Width and Height
Deep Convert Openstruct to JSON
Encoding::Undefinedconversionerror: "\Xc2" from Ascii-8Bit to Utf-8
Defined' and 'Unless' Not Working as Expected
Why Can't We Override '||' and '&&'
Accessing a Value in a Method Using *