I’m putting together a Ruby 2.0 talk for a local Ruby meetup group and I thought it wouldn’t hurt to write down what I have learned about Keyword Arguments which is a new feature in Ruby 2.0.
Lets start with some pseudo code:
1 2 3 4 5 | |
Pain points when using multiple hashes for arguments are a) if you just want
to specify html_options you need to remember at what position it was and
b) in the example above you need to set url_options to either {}, nil
or something else just to get to html_options:
1 2 3 4 | |
Keyword Arguments to the rescue!
1 2 3 4 5 | |
url_options: {} and html_options: {} looks like Ruby 1.9 Hash syntax. Here’s
how you would specify only html_options:
1 2 3 4 | |
This may seem like it just makes you type more characters but think about previously
mentioned pain points. You no longer need to be concerned about argument position
and you don’t need to care about url_options because it gets set to {} by
default.
Speaking about defaults, you have to set default value for each keyword
argument or you could use **whatever_variable_name at the end (note double **)
of method definition which will capture the rest of key/value pairs:
1 2 3 4 5 6 7 8 9 10 | |
Notice how I’m ignoring argument position and specifying url_options last but
it still assigns everything correctly. Pretty neat, right?
One more nice thing - you can use another method (of same object) to set default value and you can even reuse previous arguments. Here’s a trivial example just to showcase how it works:
1 2 3 4 5 6 7 8 9 10 11 12 | |
So there you go. I like this feature and I’m pretty sure it will be used quite a lot once Ruby 2.0 gets adopted by more developers.