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

前端 未结 5 1496
心在旅途
心在旅途 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条回答
  •  春和景丽
    2021-02-05 18:21

    It means precisely what it sounds like — classes are objects. Specifically, they are instances of the class Class, which is itself a subclass of the class Module, which in turn is a subclass of Object, just like every other class in Ruby. Like any other object in Ruby, a class can respond to messages, have its own instance variables, etc.

    As a practical example, let's take private.

    class Person
      attr_accessor :name, :height
      private
      attr_accessor :weight
    end
    

    This gives instances of Person public methods to access the person's name and height, but the accessors for the person's weight are private. BUTBUTBUT — rather than being a keyword like in most languages, private is an ordinary method of the Module class. If we wanted, we could redefine it to do something different for a particular class hierarchy.

    class RichardStallman
      def self.private(*args)
        puts "NO! INFORMATION WAS MEANT TO BE FREE!"
      end
    end
    

提交回复
热议问题