2013-03-30 69 views
0

我試圖如果我可以通過instances of classinstances of class來調用Class instance methods。因此嘗試了以下:與`類實例方法'混淆

class Foo 
    def show; p "hi" ; end 
    def self.display ; p "hello" ; end 
end 
#=> nil 

Foo.display 
#"hello" 
#=> "hello" 

Foo.new.show 
#"hi" 
#=> "hi" 

Foo.show 
#NoMethodError: undefined method `show' for Foo:Class 
#from (irb):7 
#from C:/Ruby200/bin/irb:12:in `<main>' 

但是在下面呼叫我期望相同的錯誤NoMethodError:未定義的方法`顯示」。但爲什麼不是這樣呢?

Foo.new.display 
#<Foo:0x538020> #=> nil 
foo = Foo.new 
#=> #<Foo:0x22bc438> 
foo.display 
#<Foo:0x22bc438> #=> nil 

回答

3

在所有對象上都有一個現有的方法display

class Bar 
end 

Bar.new.methods.grep(/disp/) # => [:display] 
Bar.methods.grep(/disp/) # => [:display] 

您的代碼只是將其覆蓋Foo的實例。選擇其他名稱(例如display1),您會看到預期的錯誤。

+0

讓我嘗試一些不同的東西。 :) –

+0

是的!你是對的.. OMG! :) –