Keyword parameters in Ruby
Ruby’s keyword parameters offer a mechanism for supplying arguments to a method by explicitly indicating the parameter names alongside their corresponding values. This functionality was introduced in Ruby 2.0.
It is useful when you have methods with a large number of parameters because it enhances readability and clarity.
Here is an example:
def keyword_params(a:, b: 3, c:)
puts a + b + c
end
keyword_params(a: 1, b: 2, c: 3) # 6
keyword_params(a: 0, c: 0) # 3
keyword_params(a: 0, b: 40, c: 0) # 40
Definition
When defining a method, you can specify keyword parameters using the colon (:
) syntax instead of the normal declaration of parameters:
def old_way(foo, bar)
puts foo + bar
end
old_way(1, 2) # 3
def new_way(foo:, bar:)
puts foo + bar
end
new_way(foo: 1, bar: 2) # 3
At first this might just seem a longer way to do the same thing but there are advantages. For one named params can help prevent parameter confusion. For example:
def say_name_and_age(age:, name:)
puts "Hi #{name}, you are #{age} years old!"
end
say_name_and_age(age: 111, name: "Bilbo Baggins")
# Hi Bilbo Baggins, you are 111 years old!
Usage
When you call a method with keyword parameters, you must explicitly mention the parameter names (except ones with default values):
def some_method(a:, b: "default value here")
puts "#{a}-#{b}"
end
some_method(a: "Yo", b: "Yo") # Yo-Yo
some_method(a: "Yo") # Yo-default value here
some_method(b: "Yo") # `some_method': missing keyword: :a (ArgumentError)
Default Values
You can provide many types of default values for keyword parameters:
def zoo_method(tiger_name: "jeffery", llama_age: 77)
# Use your imagination here. I have no idea what a zoo would use this method for.
end
If you don’t explicitly pass values for tiger_name
or llama_age
, the default values will be used.
Mixed with Regular Parameters
You can mix keyword parameters with regular parameters:
def mixed_method(a, b:)
puts a + b
end
mixed_method(1, b: 2) # 3
def mixed_method_with_default_values(a = 4, b: 5)
puts a + b
end
mixed_method_with_default_values() # 9
mixed_method_with_default_values(10, b: 20) # 30
Benefits of using Keyword parameters
-
Clarity: Keyword parameters make method calls more self-explanatory and improve code readability. It’s easier to understand the purpose of each argument.
-
Flexibility: You can provide parameters in any order, as long as you specify the names.
-
Defaults: Keyword parameters are useful for providing default values without relying on the order of parameters.