03/28 2013

Ruby 2.0: Keyword Arguments

Ruby’s had nice method arguments for as long as I’ve been using it: optional arguments, grabbing arguments into an array, automatically compressing a trailing hash into a single argument:

opt "okay", lets: 'do it'
# call method "opt" with first argument "okay" and second argument {:lets=>'do it'}

New in Ruby 2.0 is a rather enviable Python feature, keyword arguments:

def kw(x, y: "default y")
kw "hello", y: "hasta la vista"
# kw called with x="hello" and y="hasta la vista"

kw "oops"
# kw called with x="hello" and y="default y"

kw "hello", "friends"
# #<ArgumentError: wrong number of arguments (2 for 1)> raised

This is sometimes better than hash compression. Frequently you’ll end up setting a bunch of defaults for missing hash entries1; keyword arguments simplify that.

I put some sample code on Gist and owe quite a bit to Urabe Shyouhei for their excellent “What’s New in Ruby 2.0” slide deck.


  1. Some increasingly-worse ways to set defaults from missing hash entries can be found on Stack Overflow.