What is the &: of &:aFunction doing? [duplicate]

删除回忆录丶 提交于 2019-11-29 18:17:29

is there any way of passing variables into trigger

No.

You're invoking Symbol#to_proc which does not allow you to specify any arguments. This is a convenient bit of sugar Ruby provides specifically for invoking a method with no arguments.

If you want arguments, you'll have to use the full block syntax:

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

Symbol#to_proc is a shortcut for calling methods without parameters. If you need to pass parameters, use full form.

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

This will do exactly what you need:

def trigger(ex)
  puts ex.val
end

anArray = [Example.new(10), Example.new(21)]
anArray.each(&method(:trigger))
# 10
# 21
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!