`&:views_count` 在`Post.published.collect(&:views_count)` [英] `&:views_count` in `Post.published.collect(&:views_count)`

查看:19
本文介绍了`&:views_count` 在`Post.published.collect(&:views_count)`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了来自 这里

Post.published.collect(&:views_count)

我猜它等于

.collect { |p| p.views_count }

但是我以前从来没有见过这种用法,这有名字吗?我在哪里可以找到有关它的更多信息?

But I never saw this usage before, does this have a name? Where can I find more information about it?

推荐答案

这实际上是一个相当聪明的 hack 使其进入 ruby​​ 1.9.

This is actually a rather clever hack made it into ruby 1.9.

基本上,ruby 中变量前面的 & 将其强制转换为 proc.它通过调用 to_proc 来实现.一些聪明的家伙(我第一次看到这是在 _whys 代码中,但我不会相信他,因为我不知道他是否想出了它)在 Symbol 中添加了一个 to_proc 方法,本质上是 {|obj|obj.send self}.

Basically, & in front of a variable in ruby coerces it into a proc. It does that by calling to_proc. Some clever fellow (first time I saw this was in _whys code, but I won't credit him cause I don't know if he came up with it) added a to_proc method to Symbol, that is essentially {|obj| obj.send self}.

ruby 中的强制转换者并不多,但似乎所有强制转换者都主要用于进行这样的 hack(例如 !! 将任何类型强制转换为布尔值)

There aren't many coercians in ruby, but it seems like all of them are mostly used to do hacks like this (like !! to coerce any type into a boolean)

这篇关于`&:views_count` 在`Post.published.collect(&:views_count)`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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