Optional Method Parameters with Hashes
Monday June 29, 2009
Ruby provides a mechanism for optional method parameters. However, this mechanism is not very flexible. You cannot pass them by name, out of order, or omit some of the parameters. This article outlines how you can use hashes to emulate keyword or named parameters. This gets around these limitations with a little Ruby magic and just a little extra syntax.


Comments
Great article! I have one question though: when you call the method, how come you can use this syntax: ‘this great’)>?
I mean, how is ‘this great’> interpreted as a hash? It gives you an error if you try to just run ‘this great’> in a Ruby program. Shouldn’t you have to type ‘this great’})>?
Looks like my previous comment didn’t post correctly.
What I want to know is why you can use the :key => :value syntax in the parameter without having the hash syntax, like this: {:key => :value}
If you have any hash parameters, any key/value pairs outside of an explicit hash literal will go to the first unassigned hash parameter. For example, if I have meth( a={}, b={} ), then the method call meth( :k => ‘v’ ) will assign that key/value pair to the hash a. But if I do meth( { :test => ‘test’ }, :k => ‘v’ ), it will assign the hash literal to a, and the “naked” key/value pair to b. It’s a little quirky, so I tend to keep methods that use this syntax simple, with only one hash parameter in the method declaration.