Keyword Arguments Feature in Ruby 2.0

One of the new features of Ruby 2.0 is keyword arguments. keyword arguments make it easier create method that take optional named arguments.

keyword arguments in the method definition must be symbols given in the new-style hash syntax.
Assume we have a method:

1
2
3
4
5
6
7
8
9
def print(message: 'Hello')
  puts message
end

print #=> Hello

print(message: 'Hi') #=> Hi

print({ message: 'Hi' }) #=> Hi

Ruby 2.0 blocks can also be defined with keyword arguments:

1
2
3
4
5
6
7
8
9
define_method(:print) do |message: 'Hello'|
  puts message
end

print #=> Hello

print(message: 'Hi') #=> Hi

print({ message: 'Hi' }) #=> Hi

Keyword arguments vs Positional arguments
Assume we have a method with positional arguments:

1
2
3
4
5
def total(subtotal, tax, discount)
  subtotal + tax - discount
end

total(100, 10, 5) # => 105

This method does its job, but as a reader of the code using the total method, I have no idea what those arguments mean without looking up the implementation of the method.

By using keyword arguments, we know what the arguments mean without looking up the implementation of the called method:

1
2
3
4
5
6
7
def obvious_total(subtotal:, tax:, discount:)
  subtotal + tax - discount
end

obvious_total(subtotal: 100, tax: 10, discount: 5) # => 105

obvious_total({ subtotal: 100, tax: 10, discount: 5 }) # => 105

Keyword arguments allow us to switch the order of the arguments, without affecting the behavior of the method:

1
2
3
obvious_total(subtotal: 100, discount: 5, tax: 10) # => 105

obvious_total({ subtotal: 100, discount: 5, tax: 10 }) # => 105