Method Arguments
Prerequisites: Methods
Ruby methods can take arguments in several ways. You'll see all of these in real code.
Default values
def greet(name, greeting = "Hello")
"#{greeting}, #{name}!"
end
puts greet("Ada")
puts greet("Ada", "Welcome")
Hello, Ada!
Welcome, Ada!
Keyword arguments
Keyword arguments are passed by name, which makes calls easier to read and lets callers give them in any order:
def create_user(name:, role: "member", active: true)
"#{name} (#{role}, active: #{active})"
end
puts create_user(name: "Ada")
puts create_user(role: "admin", name: "Linus")
Ada (member, active: true)
Linus (admin, active: true)
name: with no default is required — leaving it out raises
missing keyword: :name (ArgumentError).
Compare create_user("Ada", "admin", false) — what does false mean?
Keyword arguments answer that at the call site, so prefer them for
optional settings and for methods with more than two or three
arguments.
Any number of arguments
A * before a parameter collects any number of positional arguments
into an array (this is called a splat):
def total(*prices)
prices.sum
end
p total(1, 2, 3)
p total
6
0
**options does the same for keyword arguments, collecting them into
a hash.
Common mistakes
- Putting a default positional parameter before a required one. Keep required parameters first.
- Forgetting the colon:
nameis positional,name:is a keyword.
Practice
Write format_price(amount, currency: "USD", decimals: 2) that returns
a string like "12.50 USD". Call it once with only an amount and once
with currency: "EUR".
Hint: format("%.2f", 12.5) returns "12.50". Use decimals to
build the format string.
Show solution
def format_price(amount, currency: "USD", decimals: 2)
"#{format("%.#{decimals}f", amount)} #{currency}"
end
puts format_price(12.5)
puts format_price(12.5, currency: "EUR")
12.50 USD
12.50 EUR