Hommer Smith
Hommer Smith

Reputation: 27852

Private instance method on Object behaves different than in other classes in Ruby

Here is my code inheritance using the Object class:

class Object
  private
  def talk
    puts "hi there"
  end
end

class Child
  talk  # outputs 'hi there'
end

And here is my code inheritance with a new class:

class Parent
  private
  def talk
    puts "hi there"
  end
end

class Child < Parent
  talk #`<class:Child>': undefined local variable or method `talk' for Child:Class (NameError)
end

Why would this behave differently?

Upvotes: 2

Views: 39

Answers (1)

sawa
sawa

Reputation: 168091

In both examples, you call talk within the context of Child, which is an instance of Class class.

In the first example, instance method talk is defined on Object class, which Class is a subclass of.

In the second example, instance method talk is defined on Parent class, which Class is not a subclass of.

Upvotes: 2

Related Questions