Ruby 2.0: Keyword Arguments
Message from 2022
This post is pretty old! Opinions and technical information in it are almost certainly oudated. Commands and configurations will probably not work. Consider the age of the content before putting any of it into practice.
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")
end
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.
Notes
- Some increasingly-worse ways to set defaults from missing hash entries can be found on Stack Overflow.