Skip to main content

How to Pass Keyword Arguments to a Ruby Method

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A call like make_tea('black', 0, true) works, but nobody can tell what 0 and true mean. Keyword arguments name each value, make_tea('black', milk: true), so the call explains itself and the options you leave out keep their defaults.

Syntax​

Syntax
def <name>(<positional>, <keyword>: <default>, <required_keyword>:)
end

<name>(<value>, <keyword>: <value>)
PartWhat it does
<keyword>: <default>An optional keyword argument with a default value.
<required_keyword>:A keyword argument the caller must pass.
<keyword>: <value> in the callPasses a value by name, in any order.

The Ruby methods documentation: "Keyword arguments are similar to positional arguments with default values". And: "When calling a method with keyword arguments the arguments may appear in any order."

The Example​

The example defines make_tea with one positional argument and two keyword arguments, then calls it three ways.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which defines make_tea(kind, sugar: 0, milk: false) returning a description, and puts make_tea('green'), make_tea('black', milk: true) and make_tea('mint', sugar: 2).

main.rb
def make_tea(kind, sugar: 0, milk: false)
"#{kind} tea, sugar: #{sugar}, milk: #{milk}"
end

puts make_tea('green')
puts make_tea('black', milk: true)
puts make_tea('mint', sugar: 2)

Step 2: Run It​

Terminal
ruby main.rb
Output
green tea, sugar: 0, milk: false
black tea, sugar: 0, milk: true
mint tea, sugar: 2, milk: false

A zsh terminal where ruby main.rb prints green tea with sugar 0 and milk false, black tea with milk true, and mint tea with sugar 2.

Each keyword landed on its own parameter, and the defaults covered the rest. The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Passing a keyword the method doesn't have, as in honey: trueunknown keyword: :honey (ArgumentError)Check the method's keywords
Leaving out a required keywordmissing keyword: :sugar (ArgumentError)Pass it, or give it a default
Passing a keyword's value by position, as in make_tea('green', 2)wrong number of arguments (given 2, expected 1) (ArgumentError)Name it: sugar: 2

Troubleshooting​

SymptomLikely causeFix
unknown keywordA misspelled or unsupported keywordCompare the call with the def line
wrong number of argumentsA keyword value was passed by positionPass it as name: value

FAQ​

Can a method accept any keywords?​

Yes, with a double splat: def log(message, **details) collects extra keywords into the hash details.

Do keyword arguments have to come last?​

In the call, yes: positional arguments first, then keywords.

Conclusion​

Keyword arguments pass values by name: define them as name: default or name: for required ones, and call with name: value in any order.

Additional Resources​