to_proc 方法是什么意思? [英] What does to_proc method mean?

查看:27
本文介绍了to_proc 方法是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Rails 并关注 此主题.我坚持使用 to_proc 方法.我认为符号只是字符串的替代品(它们就像字符串,但在内存方面更便宜).如果我还缺少符号的任何其他内容,请告诉我.请用简单的方式解释to_proc 的含义以及它的用途.

I am learning rails and following this thread. I am stuck with the to_proc method. I consider symbols only as alternatives to strings (they are like strings but cheaper in terms of memory). If there is anything else I am missing for symbols, then please tell me. Please explain in simple way what to_proc means and what it is used for.

推荐答案

有些方法需要一个块,对于一个块经常出现这种模式:

Some methods take a block, and this pattern frequently appears for a block:

{|x| x.foo}

人们希望以更简洁的方式来写.为了做到这一点,他们使用了以下组合:符号、方法 Symbol#to_proc、隐式类转换和 & 运算符.如果将 & 放在参数位置的 Proc 实例前面,它将被解释为块.如果您将 Proc 实例以外的其他内容与 & 结合使用,则隐式类转换将尝试使用 将其转换为 Proc 实例>to_proc 方法定义在该对象上(如果有).对于 Symbol 实例,to_proc 以这种方式工作:

and people would like to write that in a more concise way. In order to do that they use a combination of: a symbol, the method Symbol#to_proc, implicit class casting, and & operator. If you put & in front of a Proc instance in the argument position, that will be interpreted as a block. If you combine something other than a Proc instance with &, then implicit class casting will try to convert that to a Proc instance using to_proc method defined on that object if there is any. In case of a Symbol instance, to_proc works in this way:

:foo.to_proc # => ->x{x.foo}

例如,假设你写:

bar(&:foo)

& 运算符与 :foo 组合,后者不是 Proc 实例,因此隐式类转换应用 Symbol#to_proc 给它,它给出 ->x{x.foo}.& 现在适用于此并被解释为一个块,它给出:

The & operator is combined with :foo, which is not a Proc instance, so implicit class cast applies Symbol#to_proc to it, which gives ->x{x.foo}. The & now applies to this and is interpreted as a block, which gives:

bar{|x| x.foo}

这篇关于to_proc 方法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆