What does this ampersand mean?

Possible duplicate:
What does the map (&: name) mean in Ruby?
What do you call the &: operator in Ruby?

Just watch some railscast and see the code as follows:

[Category, Product, Person].each(&:delete_all) 

I know that it erases all entries for these models, but I cannot understand what this means &:delete_all .

+4
source share
3 answers

This basically shortens this:

 [Category, Product, Person].each { |e| e.delete_all } 

That is, it sends delete_all each element of the iterator.

+7
source

&: delete_all is basically converted to | obj | obj.delete_all . Ampersand calls to_proc for the current object in the loop.

+1
source

When you put a Proc pr object with & at the position of the last argument, for example, in:

 some_method(&pr) 

then the block corresponding to pr will be passed to some_method . If the non_pr object, which is not Proc , is specified as:

 some_method(&non_pr) 

then non_pr will be implicitly converted to Proc on to_proc .

For example, when non_pr is Symbol , then Symbol#to_proc , which happens something like this:

 class Symbol def to_proc proc{|obj, *args| obj.send(self, *args)} end end 

In particular, with each(&:delete_all) :delete_all.to_proc will return a Proc object:

 proc{|obj, *args| obj.delete_all(*args)} 

therefore, the corresponding block will be passed to each as follows:

 each{|obj, *args| obj.delete_all(*args)} 

Noticing that the block arity for Enumerable#each is single, this is simplified:

 each{|obj| obj.delete_all} 
+1
source

Source: https://habr.com/ru/post/1446040/


All Articles