Ruby Language Keyword Arguments

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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
# => "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"
2.0

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"


Got any Ruby Language Question?