0

Object , Class, Module , NilClass are all instances of Class.

1) First Doubt how can something be an instance of itself ? (i.e 'Class' is an instance of 'Class') or is my assumption wrong ?

2) If Object , Class ,Module etc ... are all objects then how can they have class methods ? Because class methods can only be called from classes and are not present in objects. (or is my assertion incorrect that Object, Class , Module are all objects ?)

3)If Object , Class , Module are not objects then what are they ?

3) Does a class method account for the missing method in instance a of Class and ultimately a decrease in method count ?

>> Class.methods.count

=> 82

>> a = Class.new

=> #<Class:0x1005519b8>

>> a.methods.count

=> 81
pankajdoharey
  • 1,562
  • 19
  • 30

2 Answers2

1

Class objects are indeed objects.

Class methods are actually methods defined in the class's eigenclass (singleton class). That is why those methods are not available to actual instances of said classes.

Here's a way to help you see this: first, add a singleton_class method if you don't already have it:

module Kernel
  def singleton_class
    class << self
      self
    end
  end
end

Now, try the following:

String.instance_methods
String.singleton_class.instance_methods
Class.instance_methods
Class.singleton_class.instance_methods
c = Class.new
c.instance_methods
c.singleton_class.instance_methods

This will help you gain an appreciation for what methods are available to instances of a class, versus what methods are methods on the class (i.e., instances of the class's singleton class).

(You can pass a false argument to each of those instance_methods calls to see which methods are defined for that class, and not any superclasses.)

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 1
    OK now here's as answer i was looking for ... i have been onto this for days now .. been asking a similar question on stack overflow for days, and people have been ridiculing and twisting and seem to be not getting it. I get it now. Thank-you very much Chris. :) – pankajdoharey Aug 31 '11 at 23:25
  • I'm glad to be of help. I vastly prefer the name "eigenclass" also, but I've been overruled: see http://stackoverflow.com/questions/2505067/class-self-idiom-in-ruby/2505077#2505077 and its attached comments. :-) – C. K. Young Aug 31 '11 at 23:29
  • This is very close and now i know what i have to look for further (i.e eigenclass) – pankajdoharey Aug 31 '11 at 23:29
0
  1. The Ruby core is composed by Class, Object, Module and Kernel. They're predefined, so the Class class can be an instance of itself.

  2. They have class methods because they're classes, too (and classes are objects).

  3. I can't answer it yet. I have to discover which method is missing to think in an answer.

Sony Santos
  • 5,435
  • 30
  • 41