Possible Duplicate:
What does map(&:name) mean in Ruby?
I was watching a railscast and saw this code.
[Category, Product].(&:delete_all)
In regards to clearing a database.
I asked about the line in IRC and was told
(&:delete_all)
was a shortcut for
{|model| model.delete_all}
I tested this with the following
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
I received an error saying
Wrong Argument type Symbol (expected Proc)
I also tried
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
But that still failed.
If I modified it to read
[one, two].each{|model| model.class_method}
Everything worked as expected.
So, what does &:delete_all
actually do? The docs say delete_all
is a method, so I am confused as to what is going on here.
This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
I believe Rails defines this in ActiveSupport
.
It's some Rails specific patching of Ruby, symbol to proc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With