This is so simple that I can't believe it caught me.
def meth(id, options = "options", scope = "scope")
puts options
end
meth(1, scope = "meh")
-> "meh"
I tend to use hashes for argument options just because it was how the herd did it– and it is quite clean. I thought it was the standard. Today, after about 3 hours of bug hunting, I traced down an error to this gem I happen to be using that assumes named parameters will be honored. They are not.
So, my question is this: Are named parameter officially not honored in Ruby (1.9.3), or is this a side effect of something I'm missing? If they are not, why not?
Although named parameters are not supported by the Ruby language, you can simulate them by passing your function arguments through a hash. For example:
Which can be used as follows:
Your existing code simply assigns a varaible, then passes that variable to your function. For more information see: http://deepfall.blogspot.com/2008/08/named-parameters-in-ruby.html.
What's actually happening:
There is no support* for named parameters (see below for 2.0 update). What you're seeing is just the result of assigning
"meh"
toscope
being passed as theoptions
value inmeth
. The value of that assignment, of course, is"meh"
.There are several ways of doing it:
And so on. They're all workarounds, though, for the lack of named parameters.
Edit (February 15, 2013):
* Well, at least until the upcoming Ruby 2.0, which supports keyword arguments! As of this writing it's on release candidate 2, the last before the official release. Although you'll need to know the methods above to work with 1.8.7, 1.9.3, etc., those able to work with newer versions now have the following option:
I think 2 things are happening here:
Ruby doesn't have named parameters.
The example method definition has parameters with default values.
The call site example assigns a value to a caller's-scope local variable named scope and then passes its value (meh) to the options parameter.