什么是&:of&:aFunction在做什么?

我正在审查某人的ruby代码,并在其中写了类似于:

class Example attr_reader :val def initialize(val) @val = val end end def trigger puts self.val end anArray = [Example.new(10), Example.new(21)] anArray.each(&:trigger) 

:trigger意味着采用符号并将其转换为proc

如果这是正确的,除了使用self.之外,还有任何方法可以将变量传递给触发器self.

这是相关的,但从未得到回答: http : //www.ruby-forum.com/topic/198284#863450

有没有办法将变量传递给触发器

没有。

您正在调用Symbol#to_proc ,它不允许您指定任何参数。 这是一个方便的糖,Ruby专门用于调用没有参数的方法。

如果你想要参数,你将不得不使用完整的块语法:

 anArray.each do |i| i.trigger(arguments...) end 

Symbol#to_proc是调用不带参数的方法的快捷方式。 如果您需要传递参数,请使用完整表格。

 [100, 200, 300].map(&:to_s) # => ["100", "200", "300"] [100, 200, 300].map {|i| i.to_s(16) } # => ["64", "c8", "12c"] 

这将完全符合您的需求:

 def trigger(ex) puts ex.val end anArray = [Example.new(10), Example.new(21)] anArray.each(&method(:trigger)) # 10 # 21