tags:

views:

172

answers:

2

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.

+14  A: 

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.

Pi
This is correct; if you ran your test in irb, it wouldn't work (assuming you're running Ruby 1.8.x). Try it again in script/console.
Ben Scofield
+2  A: 

It's some Rails specific patching of Ruby, symbol to proc.

Zach