Can anyone explain me this syntax:
def hello(...)
p(...).to_a
end
hello 1,2,3,4 # => [1,2,3,4]
What is type of ...
?
I think this article will help you to understand it better.
In short, this is a new "shorthand syntax" for leading arguments to make code a bit "easier", now instead of call(*args, **kws, &block)
you can just write call(...)
Here is a simple example:
def perform(*args, **kws, &block)
block.call(args, kws)
end
def call(...)
perform(...)
end
> call(1, 2, 3, k1: 4, k2: 5) {|*x| puts x}
1
2
3
{:k1=>4, :k2=>5}
This is called argument forwarding. It is similar to how super
without argument list works (i.e. forward all arguments to the super
method), but for arbitrary method delegation.
So, in this case it means "Accept arbitrary arguments and forward them to p
".
It was added in Ruby 2.7.0. Documentation is somewhat sparse at the moment, it is only documented in
NEWS
file accompanying the Ruby 2.7.0 release andIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With