具有多个参数的 Setter 方法(赋值) [英] Setter method (assignment) with multiple arguments
问题描述
我有一个自定义类并且希望能够覆盖赋值运算符.下面是一个例子:
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 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
这目前无法按预期工作.使用时
This currently doesn't work as intended. upon using
h = History.new
h.strategy = :mystrategy, :backward
[:mystrategy, :backward]
被分配给策略变量,方向变量保持 :forward
.
重要的部分是我希望能够为方向参数分配一个标准值.
[:mystrategy, :backward]
gets assigned to the strategy variable and the direction variable remains :forward
.
The important part is that I want to be able to assign a standard value to the direction parameter.
非常感谢任何可以帮助完成这项工作的线索.
Any clues to make this work are highly appreciated.
推荐答案
由于名称以=
结尾的方法的语法糖,您实际上可以将多个参数传递给方法的唯一方法是绕过语法糖并使用 send
...
Due to the syntax sugar of methods whose names end in=
, the only way that you can actually pass multiple parameters to the method is to bypass the syntax sugar and use send
…
h.send(:strategy=, :mystrategy, :backward )
...在这种情况下,您不妨使用具有更好名称的普通方法:
…in which case you might as well just use a normal method with better names:
h.set_strategy :mystrategy, :backward
但是,如果您知道数组对于参数永远不合法,您可以重写您的方法以自动取消数组值:
However, you could rewrite your method to automatically un-array the values if you knew that an array is never legal for the parameter:
def strategy=( value )
if value.is_a?( Array )
@strategy << value.first
@strategy.direction = value.last
else
@strategy = value
end
end
然而,这对我来说似乎是一个粗暴的攻击.如果需要,我会使用带有多个参数的非赋值方法名称.
This seems like a gross hack to me, however. I would use a non-assigment method name with multiple arguments if you need them.
另一个建议:如果唯一的方向是 :forward
和 :backward
呢:
An alternative suggestion: if the only directions are :forward
and :backward
what about:
def forward_strategy=( name )
@strategy << name
@strategy.direction = :forward
end
def reverse_strategy=( name )
@strategy << name
@strategy.direction = :backward
end
这篇关于具有多个参数的 Setter 方法(赋值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!