Topic: Passing hashes

I'd like to optionally pass values for keys in a hash into a method.

def my_method(somevar, my_hash={:key1 => "banana", :key2 => "orange"})
  do_things(somevar)
  do_something_with_fruit(my_hash[:key1],my_hash[:key2])
end

So is there a ruby trick to let me pass in only the keys I want to the hash when calling "my_method" and using the defaults as the rest?  Or is there a gross conditional statement behind every the rails helpers?

If art interprets our dreams, the computer executes them in the guise of programs.

-SICP (Abelson, Sussman)

Re: Passing hashes

You can use reverse_merge! for setting defaults for options. This acts just like merge, but doesn't override the keys that are already set.

Last edited by ryanb (2006-08-30 17:51:22)

Railscasts - Free Ruby on Rails Screencasts

Re: Passing hashes

Excellent.  That's elegant enough without having to introduce perl like "magic" which I hate.  Thanks!

If art interprets our dreams, the computer executes them in the guise of programs.

-SICP (Abelson, Sussman)