2013-03-30 4 views
0

Class instance methodsinstances of class으로 호출 할 수 있는지 확인하려고했습니다.클래스 인스턴스 메서드 호출과의 혼동

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

예! 당신 말이 맞아요. 세상에! :) –

관련 문제