如何传递服务对象/模块作为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