Keyword Arguments in Ruby 2.0

June 12, 2013

In the past Ruby made it easy to pass a hash to your method rather than using parameters eg:

def greeting(params)
  puts "Hello #{params[:firstname]} #{params[:lastname]}!"

greeting firstname: "John", lastname: "Doe"
# => Hello John Doe!

Ruby will interpret the arguments as a hash. The best example of consistent use of this is probably in the Rails framework. However, with the introduction of Ruby 2.0 we get keyword arguments. A feature discussed for some time that didn’t make it into Ruby 1.9. This allow you to define your methods like this:

def greeting(firstname: "John", lastname: "Doe")
  puts "Hello #{firstname} #{lastname}!"

greeting firstname: "Johnny"
# => Hello Johnny Doe!

You can still catch extra arguments like this:

def greeting(firstname: "John", lastname: "Doe", **extra)
  puts "Hello #{firstname} #{lastname}!"
  puts "#{extra[:email]}" if extra[:email]

greeting lastname: "Doé", email: ""
# => Hello John Doé!
# =>

No more messing around with a catch-all params hash.

Share this post on Twitter
Morten Møller Riis

By Morten Møller Riis

I am a programmer, sysadmin, devops. I work for Gigahost in Copenhagen, Denmark. I am based in Odense, Denmark.

Twitter   ·   LinkedIn   ·   E-mail