Ruby 2.7.0 Added Shorthand Syntax For Arguments Forwarding
September 12, 2020
Before Ruby 2.7.0, there was no shorthand syntax to delegate method arguments to another method.
We had to catch all type of arguments (positional, keyword, block) and then we were passing it to the right method.
Let's see this example:
class Player
def initialize(name, **kwargs, &block)
football_player_details(name, **kwargs, &block)
end
def football_player_details(name, age:, &block)
puts "My name is #{name} and #{block.call('football player')}. "\
"I'm #{age} years old."
end
end
Player.new("Cristiano Ronaldo", age: 35) do |profession|
"I'm an international #{profession}"
end
#output
# My name is Cristiano Ronaldo and I'm an international football player. I'm 35 years old.
The above example works fine before and after Ruby 2.7.0 .
But as we see above, we have to type little more in initialize
method to pass all type of arguments to football_player_details
method.
Also, we are creating some extra memory allocations to handle the arguments individually.
Wouldn't it be nice to have a shorthand syntax for this!
Well, Ruby 2.7.0 has a shorthand syntax for argument forwarding from one method to another.
Let's use the new shorthand syntax ...
in our example:
class Player
def initialize(...)
football_player_details(...)
end
def football_player_details(name, age:, &block)
puts "My name is #{name} and #{block.call('football player')}. "\
"I'm #{age} years old."
end
end
Player.new("Cristiano Ronaldo", age: 35) do |profession|
"I'm an international #{profession}"
end
# output
# My name is Cristiano Ronaldo and I'm an international football player. I'm 35 years old.
As we see above, we have reduced few keystrokes by using ...
and it looks more readable.
...
should always be enclosed within()
, otherwise we will get syntax error.
This shorthand syntax works very well while delegating all arguments but what if we want to delegate only leading arguments!
Unfortunately, Ruby 2.7.0 does not support this but Ruby 3.0 has added leading arguments forwarding.
info@scriptday.com