开发者

How can objects have class methods in ruby?

开发者 https://www.devze.com 2023-04-02 03:47 出处:网络
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 ?

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 c开发者_开发百科lass 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


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


  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消