Keyword Arguments
suggest changeVersions
The notes below were written for Ruby 2.0–2.3. Keyword arguments are still part of the language.
Remarks
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
# prints: Hello World
say message: "Today is Monday"
# prints: Today is Monday
As a reminder, the same method without a keyword argument would have been:
def say(message = "Hello World")
puts message
end
say
# prints: Hello World
say "Today is Monday"
# prints: Today is Monday
You can simulate keyword arguments in older Ruby versions with a Hash parameter. Libraries that still support pre-2.0 Ruby often do this:
def say(options = {})
message = options.fetch(:message, "Hello World")
puts message
end
say
# prints: Hello World
say message: "Today is Monday"
# prints: Today is Monday
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents