我在RailsCast中找到了这段代码:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
map(&:name)中的(&:name)是什么意思?
我在RailsCast中找到了这段代码:
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
map(&:name)中的(&:name)是什么意思?
当前回答
它是标签的简写。映射{|标记|tag .name}。加入(' ')
其他回答
Josh Lee的回答几乎是正确的,除了等价的Ruby代码应该如下所示。
class Symbol
def to_proc
Proc.new do |receiver|
receiver.send self
end
end
end
not
class Symbol
def to_proc
Proc.new do |obj, *args|
obj.send self, *args
end
end
end
使用这段代码,当print [[1,'a'],[2,'b'],[3,'c']].map(&:first)执行时,Ruby将第一个输入[1,'a']分割为1和'a'以给出obj 1和args* 'a'以引起错误,因为Fixnum对象1没有方法self(即:first)。
当[[1,a), (2, ' b '], [3, ' c ']] . map(&:首先)执行;
:first是一个Symbol对象,所以当&:first作为参数被赋给一个map方法时,Symbol#to_proc将被调用。 地图将呼叫信息发送到:first。参数[1,'a']的To_proc,例如:first.to_proc.call([1,'a'])被执行。 Symbol类中的to_proc过程以参数(:first)向数组对象([1,'a'])发送发送消息,例如,[1,'a'].send(:first)被执行。 遍历[[1,'a'],[2,'b'],[3,'c']]对象中的其余元素。
这是一样的执行[[1,' '],[2,' b '], [3, ' c ']]。Map (|e| e.first)表达式。
它是标签的简写。映射{|标记|tag .name}。加入(' ')
(&:name)是(&:name.to_proc)的缩写,与标签相同。映射{|t| t.name}。加入(' ')
to_proc实际上是用C语言实现的
它是tags.map(&:name.to_proc)的简写。加入(' ')
如果foo是一个带有to_proc方法的对象,那么你可以将它传递给一个名为&foo的方法,该方法将调用foo。To_proc并使用它作为方法的块。
Symbol#to_proc方法最初是由ActiveSupport添加的,但已经集成到Ruby 1.8.7中。这是它的实现:
class Symbol
def to_proc
Proc.new do |obj, *args|
obj.send self, *args
end
end
end
它的意思是
array.each(&:to_sym.to_proc)