&: 在 ruby​​ 中是什么意思,它是一个混合了符号的块吗? [英] what does &: mean in ruby, is it a block mixed with a symbol?

查看:38
本文介绍了&: 在 ruby​​ 中是什么意思,它是一个混合了符号的块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
map(&:name) 在 Ruby 中是什么意思?
Ruby/Ruby on Rails &冒号快捷方式

例如,

contacts.sort_by(&:first_name).

我明白这是做什么的,但我不明白 &: 符号,这是什么意思,它是一个带块 (&) 的符号 (:) 吗?我在哪里可以阅读更多相关信息?

I understand what this does, but I dont understand the &: notations, what does that mean, is it a symbol(:) with a block (&)? Where can I read more about it?

推荐答案

& 在方法调用中的 Proc 对象之前使用时,它会将 Proc 视为调用之后的普通块.
在方法调用中,当 & 在其他类型的对象(在您的情况下为符号 :first_name)之前使用时,它会尝试在此对象上调用 to_proc,如果它没有 to_proc方法你会得到TypeError.

When & used before Proc object in method invocation, it treats the Proc as if it was an ordinary block following the invocation.
When & used before other type of object (symbol :first_name in your case) in method invocation, it tries to call to_proc on this object and if it does not have to_proc method you will get TypeError.

通常 &:first_name&:first_name.to_proc 相同.

Symbol#to_proc 返回一个通过 sym 响应给定方法的 Proc 对象.

Symbol#to_proc Returns a Proc object which respond to the given method by sym.

:first_name.to_proc 将返回如下所示的 Proc:

:first_name.to_proc will return Proc that looks like this:

proc { |obj, *args, &block| obj.first_name(*args, &block) }

此 Proc 调用对象上原始符号指定的方法作为第一个参数传递,并将所有其余参数 + 块作为此方法参数传递.

this Proc invokes method specified by original symbol on the object passes as the first parameter and pass all the rest parameters + block as this method arguments.

再举一个例子:

> p = :each.to_proc
=> #<Proc:0x00000001bc28b0>
> p.call([1,2,3]) { |item| puts item+1 }
2
3
4
=> [1, 2, 3]

这篇关于&amp;: 在 ruby​​ 中是什么意思,它是一个混合了符号的块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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