次の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
、ブロックに2つの引数を渡すでも機能します。
%w(abecd ab cd).inject(&:gsub.with('cde'))
# => "cdeeecde"
または、[速記]ブロックを速記ブロックに渡すことで非常にクールなもの:
[['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との会話でさらに詳しく説明します。Ruby
のmap(&:method)構文に引数を指定できますか?
以下のコメントで @amcaplanが提案したように、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]]