How to Pass Keyword Arguments to a Ruby Method
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
def <name>(<positional>, <keyword>: <default>, <required_keyword>:)
end
<name>(<value>, <keyword>: <value>)
| Part | What 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 call | Passes 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:

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
ruby main.rb
green tea, sugar: 0, milk: false
black tea, sugar: 0, milk: true
mint tea, sugar: 2, milk: false

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
| Mistake | What happens | Do this instead |
|---|---|---|
Passing a keyword the method doesn't have, as in honey: true | unknown keyword: :honey (ArgumentError) | Check the method's keywords |
| Leaving out a required keyword | missing 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
| Symptom | Likely cause | Fix |
|---|---|---|
unknown keyword | A misspelled or unsupported keyword | Compare the call with the def line |
wrong number of arguments | A keyword value was passed by position | Pass 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
- Keyword arguments, in the Ruby documentation.
