Ruby 2.7 adds shorthand syntax for arguments forwarding

Ruby 2.7 added a new shorthand syntax ... for forwarding arguments to a method.

Need for a new operator

Currently we do have * and ** operators for single and keyword arguments. These are used to specify any number of arguments or convert array or hashes to several arguments.

The ... operator

The idea of ... operator is to capture all and forward arguments irrespective of type. So we can forward single, keyword arguments or blocks.

Its a shorthand syntax to forward everything. It acts similar to calling super without any arguments.

Lets take a look at it with an example. Consider we define a method that accepts some regular, keyword and block arguments.

def perform(*args, **kws, &block)
  block.call(args, kws)
end
 => :perform

Now lets define method call that simply forwards all these arguments to perform using the ... operator.

def call(...)
  perform(...)
end
 => :call

Now lets call call with some mixed arguments and also block which gets executed:

head :009 > call(1, 2, 3, k1: 4, k2: 5) {|*x| puts x}
1
2
3
{:k1=>4, :k2=>5}

What’s next

As of now, the ... operator seems to be limited to simply forwarding or delegating arguments to a method.

However, there are plans to improve upon and add more features to it, like handling lead arguments, that could make it useful in places like method_missing.

As of now this is not a valid syntax, but could be possible use case like:

def method_missing(name, ...)
  if name.to_s.end_with?('=')
    update(name, ...)
  end
end

Need help on your Ruby on Rails or React project?

Join Our Newsletter