Ruby Method definition Syntax with & keyword

Viewed 44
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?

1 Answers

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".

Related