map(&:name)在Ruby中是什么意思? [英] What does map(&:name) mean in Ruby?

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

问题描述

我在 a RailsCast 中找到了这段代码:

I found this code in a RailsCast:

def tag_names
  @tag_names || tags.map(&:name).join(' ')
end

map(&:name)中的(&:name)是什么意思?

推荐答案

这是tags.map(&:name.to_proc).join(' ')

如果foo是具有to_proc方法的对象,则可以将其作为&foo传递给方法,该方法将调用foo.to_proc并将其用作方法的块.

If foo is an object with a to_proc method, then you can pass it to a method as &foo, which will call foo.to_proc and use that as the method's block.

Symbol#to_proc方法最初由ActiveSupport添加,但已集成到Ruby 1.8.7中.这是它的实现:

The Symbol#to_proc method was originally added by ActiveSupport but has been integrated into Ruby 1.8.7. This is its implementation:

class Symbol
  def to_proc
    Proc.new do |obj, *args|
      obj.send self, *args
    end
  end
end

这篇关于map(&:name)在Ruby中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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