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]}!"
end

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}!"
end

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]
end

greeting lastname: "Doé", email: "jd@example.org"
# => Hello John Doé!
# => jd@example.org

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