Reputation: 812
Class
A
is a subclass of ClassB
. ClassB
is a subclass of classC
.a
is an object of classA
.b
is an object of classB
. Which ONE of the following Ruby expressions is NOT true?
b.respond_to?('class')
a.superclass == b.class
A.superclass == B
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
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