📜 ⬆️ ⬇️

Unary ampersand

I'll tell you how this elegant design works in Ruby:

User.all.map &:name #     

instead

 User.all.map { |user| user.name } 

At first it seems that this is a property of enumerated classes, but in reality it is not.

Magic # 1.


When ruby ​​encounters an ampersand (&) in the last argument of a method call,
then tries to turn it into an executable block of code (Proc). For example:
')
 a = (1..10).to_a a.map { |n| n*n } # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] l = lambda { |n| n*n } a.map &l # => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 


Magic # 2.


Ruby, meeting an ampersand, turns an object into a executable block by calling the #to_proc method.

And here it is the main surprise, calling Symbol's #to_proc, we get something like the following code block:

 lambda { |x| x.send(self) } 


That is, Symbol # to_proc returns exactly the block that we expected from it, because it is already defined in the Symbol class in this form.

UPD. Try on


Such a Symbol property gives an amazing opportunity to call methods, substituting objects as parameters:

 :upcase.to_proc.call "asdad" # => "ASDAD" 


Materials on the topic


blog.hasmanythrough.com/2006/3/7/symbol-to-proc-shorthand
weblog.raganwald.com/2008/06/what-does-do-when-used-as-unary.html
en.wikibooks.org/wiki/Ruby_Programming/Syntax/Method_Calls#The_ampersand_.28.26.29
m.onkey.org/let-s-start-with-wtf

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


All Articles