我收到以下错误
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中的表达式。