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

别来无恙 提交于 2019-11-28 14:05:59

问题


This question already has an answer here:

  • What does map(&:name) mean in Ruby? 15 answers

I'm reviewing someone's ruby code and in it they've written something similar to:

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)

The :trigger means the symbol is taken and the & transforms it into a proc?

If that's correct, is there any way of passing variables into trigger apart from using self.?

This is related but never answered: http://www.ruby-forum.com/topic/198284#863450


回答1:


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



回答2:


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"]



回答3:


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


来源:https://stackoverflow.com/questions/11847336/what-is-the-of-afunction-doing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!