reader of the Module calss in Ruby?

This question already has an answer here:

  • What is attr_accessor in Ruby? 18 answers

  • It works like this:

    module Attr
      attr_accessor :my_variable
    end
    
    class MyClass
      @my_variable = "hi"
      def initialize
        @my_variable = "ho"
      end
    end
    

    You include the module in the class to construct an accessor for the instance variable @my_variable :

    MyClass.include Attr
    c = MyClass.new
    c.my_variable                #=> "ho"
    c.my_variable = "huh?"       #=> "huh?"
    c.my_variable                #=> "huh?"
    

    You extend the module to the class to construct an accessor for the class instance variable @my_variable :

    MyClass.extend Attr          #=> MyClass
    MyClass.my_variable          #=> "hi"
    MyClass.my_variable = "nuts" #=> "nuts"
    MyClass.my_variable          #=> "nuts"
    c.my_variable                #=> "huh?"
    

    As you see, the instance variable @my_variable is distinct from the class instance variable @my_variable . They coexist just as they would if they had different names.

    More commonly, you'll see include and extend within the class definition, but the effect is the same as what I have above:

    class MyClass
      include Attr
      extend Attr
      @my_variable = "hi"
      def initialize
        @my_variable = "ho"
      end
    end
    
    链接地址: http://www.djcxy.com/p/25774.html

    上一篇: 在Rails中的访问器

    下一篇: 读者在Ruby模块calss?