Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ampersand operator with parameters [duplicate]

Tags:

ruby

I wonder, isn't it possible to call a method using & operator with parameters?

items.each &:my_proc # ok
items.each &:my_proc(123, "456") # ops!
like image 485
Alan Coromano Avatar asked Dec 26 '22 23:12

Alan Coromano


2 Answers

No, it's not possible. Use full form.

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

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

like image 133
Sergio Tulentsev Avatar answered Jan 11 '23 01:01

Sergio Tulentsev


You can use a bit of trickery and acheive 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 highly discourage the use in production code though, since gems etc may rely on Symbol#[]. This is just a fun thing to play around with ;-)

like image 27
Patrick Oscity Avatar answered Jan 11 '23 00:01

Patrick Oscity