You’ve probably seen this pattern before. A method has an options
hash as its last argument, which holds extra parameters:
Unfortunately, you need to extract those parameters out of the hash. And that means there’s a lot of setup to wade through before you get to the good part.
But if you changed this method to use keyword arguments in Ruby 2.0+, you wouldn’t have to pull :first_name
and :last_name
out of your hash. Ruby does it for you:
Even better, if your app uses Ruby 1.9+ hash syntax, your methods can use keyword arguments without changing those methods’ callers:
See? Those arguments are identical!
Pushing keyword argument syntax one step too far
What if you haven’t switched to the new Hash syntax, though? You could convert all your code. But, at least in Ruby 2.2.1, the old hash syntax works just fine with keyword arguments:
Nice! What about passing a hash object, instead of arguments?
Whoa. What if we want to mix a hash and keyword arguments?
OK. I guess we took that one step too far. To fix this, you could use Hash#merge to build a hash you could pass in on its own. But there’s a better way.
If you were using regular arguments instead of keyword arguments, you could splat arguments from an Array, using *
:
But is there a way to splat keyword arguments into an argument list?
It turns out there is: **
. Here’s how you’d fix that broken example with **
:
And if you’re really crazy, you can mix regular arguments, keyword arguments, and splats:
Of course, if you find yourself in the situation where that’s necessary, you probably made a mistake a lot earlier!
Capture keyword arguments the easy way
Do you know how you can turn all your method arguments into an array using *
?
This also works with keyword arguments. They’re converted to a hash, and show up as the last argument of your args
array:
But args.last[:key]
isn’t the best way to read keyword arguments grabbed this way. Instead, you can use the new **
syntax to get the keyword arguments by themselves:
With this syntax, you can access the first regular argument with args[0]
and the :key
keyword argument with keyword_args[:key]
.
… Of course, now we’re back to options hashes.
Keyword arguments are great for removing a ton of parameter extraction boilerplate from your code. And you might not even have to change any of your code to take advantage of them.
But when you write more generic methods, there are some new techniques you’ll have to learn to handle keyword arguments well. You might not have to use those techniques very often. But when you do, this power and flexibility will be there, waiting for you.