Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this work: x.map(&:+"A") [duplicate]

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.

like image 829
davej Avatar asked Mar 15 '26 01:03

davej


1 Answers

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"]
like image 105
xdazz Avatar answered Mar 18 '26 00:03

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!