'Ruby Method definition Syntax with & keyword

class ExchangeUtil
  def exchange_to(other_currency, date = Date.current, &)
      @bank.exchange_with_on(self, other_currency, date, &)
  end
end

What is the siginificance of & in method definition and method calls?



Solution 1:[1]

It's a new feature in Ruby 3.1: Anonymous block argument

It's just a shortcut for when you have a block argument for a function whose only purpose is to be passed to another function. Older syntax for that would've been

class ExchangeUtil
  def exchange_to(other_currency, date = Date.current, &block)
      @bank.exchange_with_on(self, other_currency, date, &block)
  end
end

The param &block could've had any name, like &my_block, but the name was generally meaningless, so they made it "anonymous".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1