Good explanation of ruby object model — mainly, 'classes are objects'?

前端 未结 5 1550
心在旅途
心在旅途 2021-02-05 18:08

I am studying the ruby object model and have some questions. I understand the idea that an object only stores instance variables, and methods are stored in the class, which an o

5条回答
  •  Happy的楠姐
    2021-02-05 18:29

    The notion of "classes are objects" ( as I understand it ) implies that anything you can do with an object, you can do it with a class.

    This differs from other programming languages where the class and the class definition are special artifacts different from objects and often unaccessible to the runtime.

    For instance in Ruby, you can modify any object at runtime, since classes are also objects you can modify the class it self and add methods at runtime, delete methods, or add and delete attributes at runtime.

    For instance:

    $ irb
    >> x = Object.new
    => #
    >> x.to_s
    => "#"
    >> undef to_s
    => nil
    >> x.to_s
    NoMethodError: undefined method `to_s' for #
    from (irb):4
    >> 
    

    That's not possible on other programming languages where a distinction between objects and classes is made.

    note: Probably you should understand basic Ruby concepts before going to meta programming as it may be confusing, that what I would do.

提交回复
热议问题