Ampersand with parameters

I wonder if it's possible to call the using and operator method with parameters?

items.each &:my_proc # ok items.each &:my_proc(123, "456") # ops! 
+4
source share
2 answers

No, It is Immpossible. Use the full form.

 items.each{|i| i.my_proc(123, '456')} 

Look at the source Symbol # to_proc for "why."

+7
source

You can use a little cheating and achieve something similar:

 class Symbol def [](*args) proc{|obj| obj.send(self, *args) } end end [123.456, 234.567].map(&:round[2]) #=> [123.46, 234.57] 

I am very discouraged by the use in production code, because gems, etc. can rely on Symbol#[] . This is just a fun game to play with :-)

+3
source

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


All Articles