您可以像这样在Symbol 上创建一个简单的补丁:
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
这将使您不仅可以做到这一点:
a = [1,3,5,7,9]
a.map(&:+.with(2))
# => [3, 5, 7, 9, 11]
还有很多其他很酷的东西,比如传递多个参数:
arr = ["abc", "babc", "great", "fruit"]
arr.map(&:center.with(20, '*'))
# => ["********abc*********", "********babc********", "*******great********", "*******fruit********"]
arr.map(&:[].with(1, 3))
# => ["bc", "abc", "rea", "rui"]
arr.map(&:[].with(/a(.*)/))
# => ["abc", "abc", "at", nil]
arr.map(&:[].with(/a(.*)/, 1))
# => ["bc", "bc", "t", nil]
甚至可以使用inject,它将两个参数传递给块:
%w(abecd ab cd).inject(&:gsub.with('cde'))
# => "cdeeecde"
或者将 [shorthand] 块传递到 到 速记块的超级酷的东西:
[['0', '1'], ['2', '3']].map(&:map.with(&:to_i))
# => [[0, 1], [2, 3]]
[%w(a b), %w(c d)].map(&:inject.with(&:+))
# => ["ab", "cd"]
[(1..5), (6..10)].map(&:map.with(&:*.with(2)))
# => [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]
这是我与@ArupRakshit 的对话,进一步解释:
Can you supply arguments to the map(&:method) syntax in Ruby?
正如@amcaplan 在comment below 中建议的那样,如果将with 方法重命名为call,则可以创建更短的语法。在这种情况下,ruby 为这种特殊方法 .() 提供了一个内置快捷方式。
所以你可以像这样使用上面的:
class Symbol
def call(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a = [1,3,5,7,9]
a.map(&:+.(2))
# => [3, 5, 7, 9, 11]
[(1..5), (6..10)].map(&:map.(&:*.(2)))
# => [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]