Last Updated: February 25, 2016
·
579
· antonysastre

Ruby 2.0 Quicklook: Keyword Arguments

Simply explained, keyword arguments provides a more dynamic way to define methods (and their signature) by naming the parameters passed to it.

Ruby 1.9 — you could pass a hash as an argument but needed to do some inner processing for default values:

def greet(opts={})
  greeting = opts[:greeting] || 'Hello'
  name = opts[:name] || 'World'

  puts "#{ greeting } #{ name }!"
end

Ruby 2.0 — now you can simply name the parameters straight in the method definition.

def greet(greeting: 'Hello', name: 'World')
  puts "#{ greeting } #{ name }!"
end

My Ruby 2.0 Quicklook is a short series of note-to-self about the new thingies in Ruby 2.0 in quick, simple and non-complicated explanations for forgettable future me. I hope it's of use to you as well and please feel free to comment and/or correct.