Ruby: Why calling the superclass method on an object gives an error -
class
a
subclass of classb
. classb
subclass of classc
.a
object of classa
.b
object of classb
. 1 of following ruby expressions not true?
b.respond_to?('class')
a.superclass == b.class
a.superclass == b
a.class.ancestors.include?(c)
the answer quiz question (2).
i understand why (1), (3), , (4) correct, (2) bit confusing.
(2) confusing because when input a.superclass
irb
, got nomethoderror: undefined method 'superclass' #<a:0x7fbdce1075f0>
.
but when input a.superclass == b
irb
, true
.
why can call superclass
on class not on class's object?
class c end class b < c end class < b end = a.new b = b.new p b.class p a.superclass --output:-- b 1.rb:14:in `<main>': undefined method `superclass' #<a:0x0000010109bc88> (nomethoderror)
why can call superclass on class not on class's object?
first, proper term "an instance of a". reason can call superclass() on because ruby defines class called class, , class defines methods can called class objects, instances of class. classes, e.g. a, instances of class. 1 of methods defined in class superclass().
on other hand, instance of not class, , therefore instance of cannot call methods defined in class.
you might have read "everything in ruby object" (which not true, in cases is). object (in addition being class). object must instance of class, , happens instance of class. therefore, can call methods defined in class.
Comments
Post a Comment