Lesha Pipiev
Lesha Pipiev

Reputation: 3333

Methods defined in class Object are instance and class one at the same time

How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method

Upvotes: 0

Views: 36

Answers (3)

Jörg W Mittag
Jörg W Mittag

Reputation: 369420

Every object is an instance of Object. Thus, every object will respond to boo.

Foo is an object (classes are objects, too), ergo, Foo is an instance of Object (it is an instance of Class, which is a subclass of Module, which is a subclass of Object).

Foo.new is an object (it is an instance of Foo, which is a subclass of Object).

Since both Foo and Foo.new are instances of Object, both respond to boo.

[Note: I am ignoring the existence of BasicObject.]

Upvotes: 1

spickermann
spickermann

Reputation: 106782

Perhaps forwarding the method to self is an option?

require 'forwardable'

class Foo
  extend Forwardable

  def self.boo
    'boo method'
  end

  def_delegator self, :boo
end

Foo.boo
#=> "boo method"

Foo.new.boo
#=> "boo method"

Upvotes: 1

tadman
tadman

Reputation: 211540

If you really want to do this, keep in mind that the class context and the instance context are entirely different so instance variables are not equivalent.

module FooMethods
  def boo
    'boo'
  end
end

class Foo
  extend FooMethods
  include FooMethods
end

This deliberately imports the mixin at both the class level via extend and instance level via include.

Upvotes: 1

Related Questions