Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding [ClassOne, ClassTwo].each(&:my_method) [duplicate]

Tags:

ruby

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.

like image 369
scubabbl Avatar asked Sep 19 '08 03:09

scubabbl


2 Answers

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.

like image 134
Alex M Avatar answered Oct 24 '22 11:10

Alex M


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

like image 37
Zach Avatar answered Oct 24 '22 10:10

Zach