Image for post
Image for post
Photo by Jeffrey Dungen on Unsplash

The Arguments Forwarding shorthand in Ruby 2.7

How to 3-dots operator can be used to automatically forward arguments to another method call

Mehdi Farsi
Oct 27 · 2 min read

In Ruby, it occurs that a method directly forwards arguments to another one

Here, forwarding *args, **kwargs, &blk is redundant and it impacts the readability of the code. To overcome this problem, Ruby 2.7 introduced the arguments forwarding shorthand

In the above example, everything passed to Exporter.run is forwarded to new. As new calls initialize then Exporter#initialize receives all the arguments passed to the call of Exporter.run.

Neat!

Now, what happens if Exporter.run needs to manipulate arguments to instantiate the right exporter, for example?

produces

syntax error, unexpected def self.run(type, ...)
^^^

Indeed, the arguments forwarding shorthand can’t be mixed with other arguments and it also can’t be destructured.

The above feature enhancement is in discussion since December 2019. So what if you still want to manipulate arguments before forwarding them to another method call?

In Exporter.run method, we declare a proc that takes 2 arguments:

  • *_ : regular arguments (unused in the block)
  • **kwarg : keywords arguments

In this block, we check if type passed as keyword argument is whitelisted by Exporter. If so, we instantiate the right exporter by forwarding all the arguments using the Argument Forwarding shorthand—we instantiate Exporter::CSVExporter in this case. Finally we call the generate_export method on our freshly instantiated exporter.

The block passed to our proc can manipulate the arguments because the Argument Forwarding shorthand is passed to call. So the arguments passed to call are directly passed as arguments of the block.

Until the Ruby Core Team decides (or not) to implement regular arguments mixed with the Arguments Forwarding shorthand, this is one of the only ways to manipulate the arguments list.

Voilà!

RubyCademy

E-Learning platform for Ruby and Ruby on Rails

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store