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

查看:97
本文介绍了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实例以外的其他内容与&组合,则隐式类强制转换将尝试使用在该对象上定义的to_proc方法(如果有)将其转换为Proc实例.在Symbol实例的情况下,to_proc以这种方式工作:

and people would like to write that in a more concise way. In order to do that, a symbol, the method Symbol#to_proc, implicit class casting, and & operator are used in combination. 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}

例如,假设您这样编写:

For example, suppose you write like this:

bar(&:foo)

&运算符与不是Proc实例的:foo结合使用,因此隐式类强制将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天全站免登陆