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,320
  • 5
  • 16
  • 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
  • 154,648
  • 35
  • 237
  • 264
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
  • 386,424
  • 207
  • 554
  • 861
Boris Stitnicky
  • 12,093
  • 5
  • 54
  • 73