ruby – 具有多个参数的Setter方法(赋值)
发布时间:2020-12-16 21:50:15 所属栏目:百科 来源:网络整理
导读:我有一个自定义类,希望能够覆盖赋值运算符. 这是一个例子: class MyArray Array attr_accessor :direction def initialize @direction = :forward endendclass History def initialize @strategy = MyArray.new end def strategy=(strategy,direction = :fo
我有一个自定义类,希望能够覆盖赋值运算符.
这是一个例子: 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 这似乎是对我的一个严重的骇客.如果需要,我将使用带有多个参数的非分配方法名称. 另一个建议:如果唯一的方向是:向前和向后: def forward_strategy=( name ) @strategy << name @strategy.direction = :forward end def reverse_strategy=( name ) @strategy << name @strategy.direction = :backward end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |