Setter method (assignment) with multiple arguments

后端 未结 2 1818
攒了一身酷
攒了一身酷 2020-12-10 02:17

I have a custom class and want to be able to override the assignment operator. Here is an example:

class MyArray < Array
  attr_accessor :direction
  def          


        
2条回答
  •  一整个雨季
    2020-12-10 03:00

    The problem is

    def strategy=(strategy, direction = :forward)
      @strategy = strategy
      @strategy.direction = direction
    end
    

    When you set

    h.strategy = :mystrategy, :backward
    

    you are actually overriding the original @strategy instance. After that call, @strategy is an instance of Symbol, not MyArray.

    What do you want to do? Replace the object or update it?

提交回复
热议问题