Keyword arguments were introduced in Ruby 2.0, and improved in Ruby 2.1 with the addition of required keyword arguments.
A simple method with a keyword argument looks like the following one:
def say(message: "Hello World")
puts message
end
say
# => "Hello World"
say message: "Today is Monday"
# => "Today is Monday"
As a reminder, the same method without keyword argument would have been:
def say(message = "Hello World")
puts message
end
say
# => "Hello World"
say "Today is Monday"
# => "Today is Monday"
You can simulate keyword argument in previous Ruby versions using a Hash parameter. This is still a very common practice, especially in libraries that provides compatibility with pre-2.0 Ruby versions:
def say(options = {})
message = options.fetch(:message, "Hello World")
puts
end
say
# => "Hello World"
say message: "Today is Monday"
# => "Today is Monday"