Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 我应该覆盖哪个数组方法?_Ruby - Fatal编程技术网

Ruby 我应该覆盖哪个数组方法?

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 问题

我想扩展一个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
问题:

这项工作:

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
值。