2016-12-06 71 views

回答

6

差不多。你可以讓你的模塊可轉換到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,這將工作。

+0

優秀!謝謝!我忘了to_proc。 – gayavat

1

我沒有看到這個的時候都不能在現實生活中使用,但...:

['any'].each &PrintAny.instance_method(:call).bind(Object) 
#=> any 
相關問題