Ruby 方法定义语法与 &关键词

发布于 2025-01-20 05:59:02 字数 257 浏览 1 评论 0原文

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

在方法定义和方法调用中, &amp& 的siginciencience是什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍暮颜 2025-01-27 05:59:02

是 Ruby 3.1 中的一项新功能:匿名块参数

这 只是当您有一个函数的块参数时的快捷方式,该函数的唯一目的是传递给另一个函数。较旧的语法是

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

参数 &block 可以有任何名称,例如 &my_block,但该名称通常毫无意义,所以他们做了它“匿名的”。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文