什么是和&:aFunction做什么?

时间:2012-08-07 13:42:59

标签: ruby symbols proc

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

的内容
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.之外,有没有办法将变量传递给触发器?

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:2)

  

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

没有

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

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

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

答案 2 :(得分:0)

这将完全符合您的需求:

def trigger(ex)
  puts ex.val
end

anArray = [Example.new(10), Example.new(21)]
anArray.each(&method(:trigger))
# 10
# 21