我有一個自定義類,希望能夠覆蓋賦值運算符。 這裏是一個例子:具有多個參數的Setter方法(賦值)
class MyArray < Array
attr_accessor :direction
def initialize
@direction = :forward
end
end
class History
def initialize
@strategy = MyArray.new
end
def strategy=(strategy, direction = :forward)
@strategy << strategy
@strategy.direction = direction
end
end
這目前不能按預期工作。在使用時的
h = History.new
h.strategy = :mystrategy, :backward
[:mystrategy, :backward]
獲取分配給該策略和可變的方向變量保持:forward
。
重要的是我希望能夠爲方向參數分配一個標準值。
任何線索,使這項工作受到高度讚賞。
編輯爲替代實現添加另一個建議。 – Phrogz 2012-02-14 17:05:12
我喜歡你檢查數值是否爲Array的建議。你說它是一個嚴重的黑客攻擊。哪裏會使用這個原因麻煩? – FlyingFoX 2012-02-14 17:23:25
@FlyingFoX這是一個「粗暴的黑客」,因爲它不是慣用的,不是自我記錄的,並且通常不適用(在某些人可能想要傳遞數組作爲第一個參數的情況下)。 – Phrogz 2012-02-14 17:59:26