1

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?

1 Answer 1

9
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation! The quiz problem said a is an object of class A. Is this inaccurate or imprecise, and a is an instance of A would be more accurate?
The phrase 'a is an object of class A' is also correct, but not 'a is a class object'. I guess saying "class's object" is technically correct when taking about an instance of a class, but it is confusing since it looks and sounds too much like 'class object'. In ruby "a class object" is A or B or C.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.