2013-11-26 81 views
3

元編程Ruby第3章有一個任務來編寫C#的using statement的Ruby等價物。我開始了:Ruby的使用方法是什麼?

class Resource 
    def dispose 
    @disposed = true 
    end 
    def disposed? 
    @disposed 
    end 
end 
def using(r) 
    puts "Not implemented." 
end 

r = Resource.new 
using(r) 

我還沒有執行using呢。然而,當我運行這段代碼,我得到

in `using': wrong argument type Resource (expected Module) (TypeError) 

而且,如果我喜歡寫東西using(Kernel)using(Enumerable)等,在程序完成沒有錯誤。據我所知,在Ruby中沒有using方法或關鍵字,但我也在pry和irb中獲得相同的行爲。發生什麼事?

+1

我得到「未實現。」當我運行上面的代碼時,爲我工作的方式應該是1.9.3 – hirolau

+0

您運行的是什麼ruby版本?在後面的MRI版本中不應該有一種叫'使用'的方法 – phoet

+2

你可以看到[here](http://www.ruby-doc.org/core-2.0.0/doc/syntax/refinements_rdoc.html),當我們需要使用'using'方法.'''將模塊名稱作爲參數,而不是對象。你得到了錯誤,當你通過'Resource'的實例時,'使用'用於激活細化。請參閱此博客['Refining Ruby'](http://blog.headius.com/2012/11/refining-ruby.html) –

回答

1

如果你想要做的是,在紅寶石2.1則需要修補main對象,因爲它已經有方法就像在評論中提到的真實:

self.instance_eval do 
    def using(r) 
    puts "Not implemented." 
    end 
end 
+0

謝謝。我使用2.1。 –

+0

[Documentation](http://ruby-doc.org/core-2.1.0/Module.html#method-i-using) –

1

在評論中指出有不應該是一個using方法。嘗試運行method(:using).owner以查看是否獲得更多信息。 irb上的預期結果是

"NameError: undefined method `using' for class `Object'" 

但您應該獲得您使用的來源。

相關問題