3

from what I've read,

something {|i| i.foo } 
something(&:foo)

are equivalent. So if x = %w(a b c d), why aren't the following equivalent:

x.map {|s| s.+ "A"}
x.map {&:+ "A"}

?

The first one works as expected (I get ["aA","bA","cA","dA"]), but the second one gives an error no matter what I try.

Community
  • 1
  • 1
davej
  • 1,350
  • 5
  • 17
  • 34

2 Answers2

6

Symbol::to_proc doesn't accept parameters.

You could add a to_proc method to Array.

class Array
  def to_proc
    lambda { |o| o.__send__(*self) }
  end
end

# then use it as below
x.map &[:+, "a"]
xdazz
  • 158,678
  • 38
  • 247
  • 274
1

If this worked, you'd have nothing to do as a rubyist. I wrote a whole postfix class built on #method_missing to remedy this. Simple dirty solution would be:

x = ?a, ?b, ?c

def x.rap( sym, arg )
  map {|e| e.send sym, arg }
end

x.rap :+, "A"
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74