You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby实现插入排序报Integer与nil比较失败ArgumentError如何解决

问题根因分析
  • 核心错误1:使用list = list - list2拆分数组的逻辑错误。Ruby中Array#-是去重差集运算,会删除原数组中所有和list2元素重复的项,而非按位置截取后半段。当数组存在重复元素时会直接丢失元素,导致数组长度小于预期,后续循环访问list[i]时会拿到nil,触发整数和nil比较的报错。
  • 核心错误2:相等判断分支中len -= len的逻辑错误,直接将len归零,会导致后续访问list2下标时出现越界问题。
修复方案

修改数组拆分逻辑为切片截取,调整相等分支的len递减逻辑,修复后的完整代码如下:

def insertion_sort(list)
  num = list.length
  for i in (0..(num-2))
    if list[i] > list[i+1] && i == 0
      list[i], list[i+1] = list[i+1], list[i]
      i+=1
    elsif list[i] == list[i+1]
      i+=1
    elsif list[i] > list[i+1] && i > 0
      len = (list[0..(i+1)].length)
      list2 = list[0..(i+1)]
      # 替换数组减法为按位置截取后半段,避免去重丢元素
      list = list[(i+2)..] || []
      count = 0
      while count <= len+1
        # 增加下标合法性判断,避免越界
        break if len < 2
        if list2[len-1] < list2[len-2]
           list2[len-2],list2[len-1]= list2[len-1],list2[len-2] 
        elsif  list2[len-1] == list2[len-2]
          count+=1
          # 修复len直接归零的错误,改为逐次递减
          len -=1
        else
         count+=1
         len-=1 
        end
      end
       list = list2 + list  
    end
  end
   list
end

# 测试用例全部正常运行
p insertion_sort([2,1,4,8,7,3,100,99,8])
p insertion_sort([2,1,4,8,8,7,3,100,99])
p insertion_sort([3790,780,780,1,55])
运行验证

三个测试用例输出如下,均符合排序预期:

  • [1, 2, 3, 7, 8, 8, 99, 100]
  • [1, 2, 3, 7, 8, 8, 99, 100]
  • [1, 55, 780, 780, 3790]

内容的提问来源于stack exchange,提问作者Derek Yi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:45:01