If you are reasonable rails developer, you are so familiar with " &:symbol ". Have you thought how it work?
Start with '&' operator. If you pass something with '&' to method, ruby think the something is a Proc object. However, when it isn't Proc object, ruby call to_proc method of the something to get Proc object. Let's see example code.
Ok. Modify it.
Yeah. Same effect is happened in Symbol class.
Symbol#to_proc method return like as:
Unfortunately, until ruby 1.8.6 doesn't have to_proc method in Symbol class, so rails defined to_proc in Symbol class. You can find it in 'activesupport-2.1.1/lib/active_support/core_ext/symbol.rb'. So if you want to use &:symbol in ruby(not in rails) that version is earlier than 1.8.7, you should define to_proc your self.
However, the Symbol#to_proc was included since 1.8.7, so you can use it without define it yourself.
Finally, let's dig to 'activesupport-2.1.1/lib/active_support/core_ext/enumerable.rb'. You can see sum method in the file like below:
Start with '&' operator. If you pass something with '&' to method, ruby think the something is a Proc object. However, when it isn't Proc object, ruby call to_proc method of the something to get Proc object. Let's see example code.
class MineWhen you run above code, you will get error message: wrong argument type Mine (expected Proc) (TypeError)
end
def method(&block)
end
m = Mine.new
method(&m)
Ok. Modify it.
class MineThe running result is : Wow.
def to_proc
Proc.new { puts "Wow" }
end
end
def method(&block)
block.call
end
m = Mine.new
method(&m)
Yeah. Same effect is happened in Symbol class.
class TerminatorThe result is : I'm a machine!! I'll be back!!
def who_am_i
puts "I'm a machine!! I'll be back!!"
end
def order(&block)
block.call self
end
end
t100 = Terminator.new
t100.order(&:who_am_i)
Symbol#to_proc method return like as:
Proc.new { |obj, *args| obj.send(self, *args) }so when you pass &:who_am_i, it works like t100.send(:who_am_i) and it same as t100.who_am_i.
Unfortunately, until ruby 1.8.6 doesn't have to_proc method in Symbol class, so rails defined to_proc in Symbol class. You can find it in 'activesupport-2.1.1/lib/active_support/core_ext/symbol.rb'. So if you want to use &:symbol in ruby(not in rails) that version is earlier than 1.8.7, you should define to_proc your self.
However, the Symbol#to_proc was included since 1.8.7, so you can use it without define it yourself.
Finally, let's dig to 'activesupport-2.1.1/lib/active_support/core_ext/enumerable.rb'. You can see sum method in the file like below:
def sum(identity = 0, &block)Above code and Symbol#to_proc method make our life is easyer and butiful. It's so great, isn't it?
return identity unless size > 0
if block_given?
map(&block).sum
else
inject { |sum, element| sum + element }
end
end



덧글