4

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!
Alan Coromano
  • 24,958
  • 53
  • 135
  • 205

2 Answers2

7

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".

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
3

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 ;-)

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168