Arguments: splats and kwargs
| Collect with * | |
| Forward with ... | |
| Keyword arguments | |
| Defaults and required kwargs |
Collect with *
A splat parameter collects extra positional arguments into one array.
Callers pass any count of numbers, and the method iterates them as usual.
def total(*numbers)
sum = 0
numbers.each do |n|
sum += n
end
sum
end
puts total(1, 2, 3)
ruby splat_demo.rb
6
Forward with ...
Three dots forward every argument, including blocks, to another method untouched.
The wrapper adds logging while compute keeps the real logic and the original signature.
def logged(...)
puts "Calling"
compute(...)
end
def compute(a, b)
a + b
end
puts logged(2, 3)
ruby forward_demo.rb
Calling
5
Keyword arguments
Keyword arguments label each value at the call site, so long parameter lists stay readable.
Callers use the name colon syntax, and Ruby raises when a required key is missing.
def greet(name:, greeting: "Hello")
puts "#{greeting}, #{name}"
end
greet(name: "Ada")
greet(name: "Ada", greeting: "Hi")
ruby kwargs_demo.rb
Hello, Ada
Hi, Ada
Defaults and required kwargs
Defaults make arguments optional, while a bare keyword with no default stays required.
Localhost and the default port fill in automatically, but timeout must always be given.
def connect(host: "localhost", port: 5432, timeout:)
puts "#{host}:#{port} (#{timeout}s)"
end
connect(timeout: 5)
ruby connect_demo.rb
localhost:5432 (5s)
Next: Rake tasks
Article author: Arthur Isaev