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


class a subclass of class b. class b subclass of class c. a object of class a. b object of class b. 1 of following ruby expressions not true?

  1. b.respond_to?('class')
  2. a.superclass == b.class
  3. a.superclass == b
  4. 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

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -