具有多个参数的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
。
重要的是我希望能够为direction参数分配标准值。
任何提供这项工作的线索都受到高度赞赏。
由于名称以=
结尾的方法的语法糖,实际上将多个参数传递给方法的唯一方法是绕过语法糖并使用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
然而,这对我来说似乎是一个严重的黑客攻击。 如果需要,我会使用带有多个参数的非assigment方法名称。
另一种建议:如果唯一的指示是:forward
和:backward
:
def forward_strategy=( name ) @strategy << name @strategy.direction = :forward end def reverse_strategy=( name ) @strategy << name @strategy.direction = :backward end
问题是
def strategy=(strategy, direction = :forward) @strategy = strategy @strategy.direction = direction end
当你设置
h.strategy = :mystrategy, :backward
你实际上是在重写原始的@strategy
实例。 在那次调用之后, @strategy
是Symbol
一个实例,而不是MyArray
。
你想让我做什么? 替换对象或更新它?