Arup Rakshit
Arup Rakshit

Reputation: 118261

confusion with `Class instance methods` call

I was trying if I can call Class instance methods by the instances of class or not. Accordingly tried the below:

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>'

But in the below call I expect the same error as NoMethodError: undefined method `display'. But why is it not the case?

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

Upvotes: 0

Views: 35

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

There is an existing method display on all objects.

class Bar
end

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

Your code just overwrites it for instances of Foo. Choose another name (display1, for example) and you'll see expected error.

Upvotes: 3

Related Questions