Method arguments in Ruby
Defaults, keyword arguments and splats on ordinary methods.
def brew(drink, size: "medium", extra_shot: false)
desc = "#{size} #{drink}"
desc += " + shot" if extra_shot
desc
end
puts brew("latte")
puts brew("mocha", size: "large", extra_shot: true)
# a splat parameter collects any number of positional arguments
def total(*prices, tax: 0.0)
(prices.sum * (1 + tax)).round(2)
end
puts total(3.5, 4.25)
puts total(10, 20, tax: 0.08)
How it works
- Keyword arguments with defaults document the call site.
- Callers override only the keywords they care about.
*pricescollects any number of positional arguments into an array.
Keywords and builtins used here
brewdefendifputstotal
The run, in numbers
- Lines
- 16
- Characters to type
- 374
- Tokens
- 112
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 79 seconds.
Step 1 of 3 in Methods & blocks, step 16 of 29 in Language basics.