attr_accessor for array?

后端 未结 4 1833
孤独总比滥情好
孤独总比滥情好 2021-02-19 09:33

I want to have an array as a instance variable using attr_accessor.

But isn\'t attr_accessor only for strings?

How do I use it on an ar

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 10:21

    Re your update:

    Although you can implement a class which acts as you describe, it is quite unusual, and will probably confuse anyone using the class.

    Normally accessors have setters and getters. When you set something using the setter, you get the same thing back from the getter. In the example below, you get something totally different back from the getter. Instead of using a setter, you should probably use an add method.

    class StrangePropertyAccessorClass
    
      def initialize
        @data = []
      end
    
      def array=(value)   # this is bad, use the add method below instead
        @data.push(value)
      end
    
      def array
        @data
      end
    
    end
    
    object = StrangePropertyAccessorClass.new
    
    object.array = "cat"
    object.array = "dog"
    pp object.array
    

    The add method would look like this:

      def add(value)
        @data.push(value)
      end
    
    ...
    
    object.add "cat"
    object.add "dog"
    pp object.array
    

提交回复
热议问题