1. Home
  2. Computing & Technology
  3. Ruby
photo of Amanda & Michael Morin
Amanda and Michael's Ruby Blog

By Amanda & Michael Morin, About.com Guides to Ruby

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

July 2, 2009 at 10:07 am
(1) Karl Lindström says:

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’})>?

July 2, 2009 at 10:11 am
(2) Karl Lindström says:

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}

July 3, 2009 at 10:04 am
(3) ruby says:

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.

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss
Community Forum
Explore Ruby
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Ruby

©2009 About.com, a part of The New York Times Company.

All rights reserved.