调试Ruby脚本错误} undefined .length方法“用于冒泡排序

时间:2015-08-19 20:48:39

标签: ruby

我收到以下错误

bubble_sort.rb:38:in `block in <main>': undefined method `length' for nil:NilClass (NoMethodError)
    from bubble_sort.rb:27:in `block (2 levels) in bubble_sort_by'
    from bubble_sort.rb:25:in `each'
    from bubble_sort.rb:25:in `each_with_index'
    from bubble_sort.rb:25:in `block in bubble_sort_by'
    from bubble_sort.rb:22:in `loop'
    from bubble_sort.rb:22:in `bubble_sort_by'
    from bubble_sort.rb:37:in `<main>'

当我运行以下脚本

def bubble_sort_by(array)

    loop do
        swap_count = 0

        array.each_index do |index| 

            if yield(array[index], array[index + 1]) > 0
                array[index], array[index + 1] = array[index + 1], array[index]
                swap_count += 1 
            end
        end
        break if swap_count == 0
    end
    array
end

bubble_sort_by(["hi","hello","hey"]) do |left,right|
   left.length - right.length
 end

我把它与另一个相似的代码进行了比较,但是使用while循环迭代数组索引。我花了两个小时研究它,我不明白为什么解释器在这个脚本中不会识别array[index].length,而它会识别IRB中的表达式。

0 个答案:

没有答案