Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the 3-dots method argument in Ruby?

Tags:

ruby

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 ... ?

like image 964
3 revsRoger Pate Avatar asked Oct 12 '20 17:10

3 revsRoger Pate


2 Answers

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}
like image 163
Alex Holubenko Avatar answered Sep 28 '22 10:09

Alex Holubenko


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

  • the NEWS file accompanying the Ruby 2.7.0 release and
  • Feature request #16253 Shorthand "forward everything" syntax.
like image 33
Jörg W Mittag Avatar answered Sep 28 '22 09:09

Jörg W Mittag