如何将服务 objects/modules 作为参数传递给 ruby
How to pass service objects/modules as arguments in ruby
是否可以使用模块或对象作为 ruby 中每个方法的参数?
我需要类似的东西。
module PrintAny
def call(text)
puts text
end
end
["any"].each PrintAny
我不知道什么时候可以在现实生活中使用它,但是...:[=11=]
['any'].each &PrintAny.instance_method(:call).bind(Object)
#=> any
差不多。您可以使您的模块可转换为 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
,这将起作用。
是否可以使用模块或对象作为 ruby 中每个方法的参数?
我需要类似的东西。
module PrintAny
def call(text)
puts text
end
end
["any"].each PrintAny
我不知道什么时候可以在现实生活中使用它,但是...:[=11=]
['any'].each &PrintAny.instance_method(:call).bind(Object)
#=> any
差不多。您可以使您的模块可转换为 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
,这将起作用。