如何用一个参数简化 ruby 块?
我在某个地方看到了一种用一个参数简化 ruby 块的方法,它基本上省略了竖线和参数声明,因为它以某种方式内联。
我无法再找到它或记住要搜索的任何名称。
Somewhere I saw a way to simplify ruby blocks with one argument, it basically omitted vertical bars and argument declaration, because it was somehow inlined.
I cannot find it anymore or remember any names to search for.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一种简化方法适用于某些情况。
如果您有类似的内容:
您可以将其简化为:
&
通过调用Symbol#to_proc
。它不适用于其他参数,并且仅当您想直接在块参数上调用方法时才有效。它是在 Rails (ActiveSupport) 中引入,但是它进入核心 Ruby 1.8.7 和 1.9。There is a simplifications that works in a few situations.
If you have something like:
You can simplify it to:
The
&
converts the symbol to a proc by callingSymbol#to_proc
. It doesn't work with additional arguments, and it only works if you want to invoke a method directly on the block argument. It was introduced in Rails (ActiveSupport), but made its way into core Ruby 1.8.7 and 1.9.