Lorsque vous mettez un objet Proc
pr
avec &
dans la dernière position de l'argument comme dans:
some_method(&pr)
puis, un bloc correspondant à pr
sera transmis à some_method
. Si un objet non_pr
qui n'est pas une Proc
est donnée comme:
some_method(&non_pr)
alors, non_pr
sera implicitement convertie à un Proc
par to_proc
.
Par exemple, lorsque non_pr
est un Symbol
, alors Symbol#to_proc
sera appliqué, qui se trouve être quelque chose comme ceci:
class Symbol
def to_proc
proc{|obj, *args| obj.send(self, *args)}
end
end
particulièrement avec each(&:delete_all)
, le :delete_all.to_proc
retournera l'objet Proc
:
proc{|obj, *args| obj.delete_all(*args)}
donc le bloc correspondant sera passé à each
comme ceci:
each{|obj, *args| obj.delete_all(*args)}
Remarquant que le arité d'un bloc pour Enumerable#each
est l'un, cela est simplifié à:
each{|obj| obj.delete_all}
C'est un double de pas moins de 20 autres questions qui ont déjà été posées et répondues ici sur StackOverflow : [Présentation \ [ClassOne, ClassTwo \] .each \ (&: mon_méthode \)] (http://StackOverflow.Com/q/99318/), [Que signifie 'map (&: nom)' dans Ruby? ] (http://StackOverflow.Com/q/1217088/), [Quel est exactement '&: capitalize' dans Ruby?] (http://StackOverflow.Com/q/1792683/), [Ruby/Ruby on Rails raccourci du côlon d'esperluette] (http://StackOverflow.Com/q/1961030/), [syntaxe de Ruby: '&: symbol'] (http://StackOverflow.Com/q/2096975/), ... –
... [Qu'est-ce que ce '&: last' Ruby Construct appelé?] (http://StackOverflow.Com/q/2211751/), [Comment appelez-vous l'opérateur '&:' dans Ruby?] (http://StackOverflow.Com/q/2259775/), [Que fait ' map (&: name) 'faire dans ce code Ruby?] (http://StackOverflow.Com/q/2388337/), [Que sont': + 'et' & + 'dans ruby?] (http: // StackOverflow.Com/q/2697024/), ['&: views_count' dans' Post.published.collect (&: views_count) '] (http://StackOverflow.Com/q/3888044/), [Syntaxe Ruby Proc] (http://StackOverflow.Com/q/4512587/), [Comment fonctionne "' (1..4) .inject (&: +) '" fonctionne dans Ruby] (http://StackOverflow.Com/q/ 5003257 /), ... –
... [Ruby map method syntax question] (http://StackOverflow.Com/q/5231919/), [Que fait l'instruction suivante '&: property'?] (Http://StackOverflow.Com/ q/5620411 /), [Que signifie le '&' dans la syntaxe suivante de ruby?] (http://StackOverflow.Com/q/5952175/), [Pourquoi utiliser l'opérateur unaire sur une propriété dans ruby? ie '&: first'] (http://StackOverflow.Com/q/6289084/), [comment' Array # map' a-t-il un paramètre pour faire quelque chose comme ça?] (http://StackOverflow.Com/q/ 6716629 /), [qu'est-ce que '&:' signifie en ruby, est-ce un bloc mélangé avec un symbole?] (Http://StackOverflow.Com/q/9188362/), ... –