Ruby 我应该覆盖哪个数组方法?
我想扩展一个Ruby数组对象,使其在为nil时返回Array.new 我的解决方案: 覆盖Ruby 我应该覆盖哪个数组方法?,ruby,Ruby,我想扩展一个Ruby数组对象,使其在为nil时返回Array.new 我的解决方案: 覆盖[]和上的 module NullSafeArray def at(index) value = super return Array.new if value.nil? value end def [](index) value = super return Array.new if value.nil? value end end 问题
[]
和上的
module NullSafeArray
def at(index)
value = super
return Array.new if value.nil?
value
end
def [](index)
value = super
return Array.new if value.nil?
value
end
end
问题:
这项工作:
assert_equal Array.new [].to_be_null_safe[3]
但这将失败:
a, b = [nil, 2].to_be_null_safe
assert_equal Array.new, a
要执行此操作,还应覆盖哪个方法
更新:
你的答案应该是:
a, b = [9].to_null_safe
assert a == 9
assert b == Array.new
它可以是a、b、c、d=
。你不知道有多少个逗号
通过查看Ruby的源代码,我想您知道要覆盖什么方法了,我试过了,但很难找到它。只需像下面这样扩展数组类
class Array
def to_null_safe!
each_with_index do |variable, index|
self[index] = "HELLO" if variable.nil?
end
end
end
类数组
def到_null_安全!
每个_带有_索引do |变量,索引|
self[index]=“HELLO”如果变量为.nil?
结束
结束
结束
只需像下面这样扩展数组类
class Array
def to_null_safe!
each_with_index do |variable, index|
self[index] = "HELLO" if variable.nil?
end
end
end
类数组
def到_null_安全!
每个_带有_索引do |变量,索引|
self[index]=“HELLO”如果变量为.nil?
结束
结束
结束
也考虑使用自定义对象,如果需要重写很多方法,而不是凌乱<代码>数组空间。< /P>
也考虑使用自定义对象,如果需要重写很多方法,而不是凌乱<代码>数组 Studio。< /P> <代码> toBeByNulLySuthaby>代码>方法是什么?它是否返回
数组
子类的实例?to\u be\u null\u safe
方法做什么?它是否返回数组
的子类的实例?我想你应该将你的方法命名为,以确保安全代码>。我说得对吗?我想你应该把你的方法命名为,以确保安全代码>。我说得对吗?这还将转换false
值。这还将转换false
值。