Ganesh
Ganesh

Reputation: 2004

ruby method is acting as instance method as well as class method

In irb console I have created one class 'Hello'

irb(main):001:0> class Hello
irb(main):002:1> end
=> nil

and created one method outside of 'Hello' class with name 'hi'

irb(main):003:0> def hi
irb(main):004:1> 'hiiii'
irb(main):005:1> end
=> :hi

Now this hi method is acting as class method as well as instance method

irb(main):006:0> Hello.hi
=> "hiiii"
irb(main):007:0> Hello.new.hi
=> "hiiii"
irb(main):008:0> hi
=> "hiiii"

why this hi method is get invoke using class 'Hello' even though it is outside of 'Hello' class context ?

Upvotes: 1

Views: 87

Answers (1)

Jordan Running
Jordan Running

Reputation: 106097

Methods defined in the "main" context (i.e. not within a class or module declaration) are defined on Object. Since every class, including (big-C) Class, inherits from Object, the method then exists in the inheritance chain of every object and every class. You can observe the same behavior by defining a method explicitly on Object:

class Object
  def foo
    puts "Hello"
  end
end

class Bar; end

Bar.foo
# => Hello

Bar.new.foo
# => Hello

foo
# => Hello

Upvotes: 6

Related Questions