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
No.
You’re invoking
Symbol#to_procwhich 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: