user86408
user86408

Reputation: 812

Ruby: Why calling the superclass method on an object gives an error

Class A is a subclass of Class B. Class B is a subclass of class C. a is an object of class A. b is an object of class B. Which ONE of the following Ruby expressions is NOT true?

  1. b.respond_to?('class')
  2. a.superclass == b.class
  3. A.superclass == B
  4. a.class.ancestors.include?(C)

The answer to this quiz question was (2).

I understand why (1), (3), and (4) are correct, but (2) is a bit confusing.

(2) is confusing because when I input a.superclass into irb, I got NoMethodError: undefined method 'superclass' for #<A:0x7fbdce1075f0>.

But when I input A.superclass == B into the irb, I get true.

Why can I call superclass on a class but not on the class's object?

Upvotes: 1

Views: 2676

Answers (1)

7stud
7stud

Reputation: 48649

class C
end

class B < C
end

class A < B
end

a = A.new
b = B.new

p b.class
p a.superclass


--output:--
B

1.rb:14:in `<main>': undefined method `superclass' for #<A:0x0000010109bc88> (NoMethodError)

Why can I call superclass on a class but not on the class's object?

First, the proper term is "an instance of A". The reason you can call superclass() on A is because ruby defines a class called Class, and Class defines the methods that can be called by class objects, which are instances of Class. All classes, e.g. A, are instances of Class. One of the methods defined in Class is superclass().

On the other hand, an instance of A is not a class, and therefore an instance of A cannot call methods defined in Class.

You might have read that "everything in ruby is an object" (which is not true, but in most cases it is). So A is an object (in addition to being a class). An object must be an instance of some class, and it so happens that A is an instance of Class. Therefore, A can call the methods defined in Class.

Upvotes: 9

Related Questions