1
是否有可能使用模塊或對象作爲每個方法的參數在紅寶石?如何傳遞服務對象/模塊作爲ruby參數
我需要類似的東西。
module PrintAny
def call(text)
puts text
end
end
["any"].each PrintAny
是否有可能使用模塊或對象作爲每個方法的參數在紅寶石?如何傳遞服務對象/模塊作爲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