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.

4

2 回答 2

6

Symbol::to_proc不接受参数。

您可以将to_proc方法添加到Array.

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

# then use it as below
x.map &[:+, "a"]
于 2012-10-02T02:55:36.593 回答
1

如果这行得通,那么作为一名红宝石学家,您将无事可做。我写了一个完整的后缀类#method_missing来解决这个问题。简单的肮脏解决方案是:

x = ?a, ?b, ?c

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

x.rap :+, "A"
于 2012-10-02T02:41:23.400 回答