rubyの各メソッドの引数としてモジュールまたはオブジェクトを使用できますか?rubyの引数としてサービスオブジェクト/モジュールを渡す方法
私は何かが必要です。
module PrintAny
def call(text)
puts text
end
end
["any"].each PrintAny
rubyの各メソッドの引数としてモジュールまたはオブジェクトを使用できますか?rubyの引数としてサービスオブジェクト/モジュールを渡す方法
私は何かが必要です。
module PrintAny
def call(text)
puts text
end
end
["any"].each PrintAny
ほとんど。あなたはその方法をPROCにあなたのモジュール変換可能を作成し、それを使用することができます:
module PrintAny
def self.print(text)
puts text
end
def self.to_proc
method(:print).to_proc
end
end
["any"].each &PrintAny # => prints "any"
Enumerable#each
はアンパサンド演算子(&
)が最初にそのオブジェクトにto_proc
を呼び出すことによってブロックするために、オブジェクトを変換し、ブロックを渡す必要があります。モジュールは単なるオブジェクトなので、メソッドがto_proc
の場合、これは機能します。
これは、今まで実生活で使用することができたとき、私は見ませんが、...:
['any'].each &PrintAny.instance_method(:call).bind(Object)
#=> any
優秀!ありがとう!私はto_procを忘れていた。 – gayavat