Adding an instance variable to a class in Ruby

前端 未结 8 585
太阳男子
太阳男子 2021-01-31 02:39

How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I\'m looking for a metaprogramming so

8条回答
  •  离开以前
    2021-01-31 03:23

    You can use attribute accessors:

    class Array
      attr_accessor :var
    end
    

    Now you can access it via:

    array = []
    array.var = 123
    puts array.var
    

    Note that you can also use attr_reader or attr_writer to define just getters or setters or you can define them manually as such:

    class Array
      attr_reader :getter_only_method
      attr_writer :setter_only_method
    
      # Manual definitions equivalent to using attr_reader/writer/accessor
      def var
        @var
      end
    
      def var=(value)
        @var = value
      end
    end
    

    You can also use singleton methods if you just want it defined on a single instance:

    array = []
    
    def array.var
      @var
    end
    
    def array.var=(value)
      @var = value
    end
    
    array.var = 123
    puts array.var
    

    FYI, in response to the comment on this answer, the singleton method works fine, and the following is proof:

    irb(main):001:0> class A
    irb(main):002:1>   attr_accessor :b
    irb(main):003:1> end
    => nil
    irb(main):004:0> a = A.new
    => #
    irb(main):005:0> a.b = 1
    => 1
    irb(main):006:0> a.b
    => 1
    irb(main):007:0> def a.setit=(value)
    irb(main):008:1>   @b = value
    irb(main):009:1> end
    => nil
    irb(main):010:0> a.setit = 2
    => 2
    irb(main):011:0> a.b
    => 2
    irb(main):012:0> 
    

    As you can see, the singleton method setit will set the same field, @b, as the one defined using the attr_accessor... so a singleton method is a perfectly valid approach to this question.

提交回复
热议问题