Ruby 3.0 Added Leading Arguments Forwarding

September 12, 2020

Ruby 2.7.0 introduced a shorthand syntax to forward arguments to another method.

Although ... is a nice addition to Ruby 2.7.0 but it does not help if we want to be little selective like catching one argument and passing the rest to another method.

Let's see an example:

class Football def bio(name, age:, &block) puts "My name is #{name} and #{block.call('football player')}. "\ "I'm #{age} years old." end end class Player def method_missing(method_name, klass_name, ...) klass = Kernel.const_get(klass_name) klass.new.send(method_name, ...) end end Player.new.bio("Football", "Cristiano Ronaldo", age: 35) do |profession| "I'm an international #{profession}" end

The above example is a classic case of using Ruby's method_missing which by default gets the missing method name method_name as positional argument and then rest of the arguments.

We have used the ... to delegate arguments to Football#bio method.

In Ruby 2.7.0, the above syntax will raise syntax error because it does not allow to specify any other argument.

That means we have to either use def method_missing(...) or use the traditional style like def method_missing(method_name, klass_name, **keargs, &block) .

But def method_missing(...) syntax will not be very helpful as we will not get hold off the method_name as shown in the above example.

Ruby 3.0 has considered this use case and allows to pass leading arguments to another method.

The above example should work fine with Ruby 3.0 .

Here is the link to the proposal.

Got something to share with us ? Please inbox

info@scriptday.com

© All rights reserved 2020