我有一个自定义类,希望能够覆盖赋值运算符。 这是一个例子:
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
。
重要的是我希望能够为方向参数分配一个标准值。
非常感谢任何使这项工作成功的线索。
最佳答案
由于名称以=
结尾的方法的语法糖,您可以实际将多个参数传递给该方法的唯一方法是绕过语法糖并使用send
…
h.send(:strategy=, :mystrategy, :backward )
...在这种情况下,您还不如使用具有更好名称的普通方法:
h.set_strategy :mystrategy, :backward
但是,您可以重写您的方法以自动取消对值的排列,如果您知道数组对参数来说永远不合法的话:
def strategy=( value )
if value.is_a?( Array )
@strategy << value.first
@strategy.direction = value.last
else
@strategy = value
end
end
然而,这对我来说似乎是一个粗暴的 hack。如果您需要的话,我会使用带有多个参数的非赋值方法名称。
另一种建议:如果唯一的方向是 :forward
和 :backward
那么:
def forward_strategy=( name )
@strategy << name
@strategy.direction = :forward
end
def reverse_strategy=( name )
@strategy << name
@strategy.direction = :backward
end
关于ruby - 具有多个参数的 Setter 方法(赋值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280623/