attr_accessor for array?

后端 未结 4 1820
孤独总比滥情好
孤独总比滥情好 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:18

    I think there is a case for this usage. Consider

    begin
      result = do_something(obj)
      # I can't handle the thought of failure, only one result matters!
      obj.result = result
    rescue
      result = try_something_else(obj)
      # okay so only this result matters!
      obj.result = result
    end
    

    And then later

    # We don't really care how many times we tried only the last result matters
    obj.result
    

    And then for the pro's we have

    # How many times did we have to try?
    obj.results.count
    

    So, I would:

    attr_accessor :results
    
    def initialize
      @results = []
    end
    
    def result=(x)
      @results << x
    end
    
    def result
      @results.last
    end
    

    In this way result behaves as you would expect, but you also get the benefit of accessing the past values.

提交回复
热议问题