范围循环单独工作,但不在until循环内

时间:2014-06-22 22:00:54

标签: ruby

def bubble_sort(arr)
    sorted = false
    until sorted
        sorted = true
        (0...arr.length-2).each do |i|
            if arr[i] > arr[i+1]
                arr[i], arr[i+1] = arr[i+1], arr[i]
                sorted = false
            end
        end
    end
    arr
end

bubble_sort([4,6,2,8,1])

以下是错误消息:

(eval):367: (eval):367: compile error (SyntaxError)
(eval):359: syntax error, unexpected kDO_COND, expecting kEND
        (0...arr.length-2).each do |i|
                                  ^
(eval):367: syntax error, unexpected kEND, expecting $end

我不明白为什么会说意外的kEND

1 个答案:

答案 0 :(得分:1)

appears to be a bug in Ruby 1.8.7 - 将do/end替换为{}

    (0...arr.length-2).each do |i|
        if arr[i] > arr[i+1]
            arr[i], arr[i+1] = arr[i+1], arr[i]
            sorted = false
        end
    end

    (0...arr.length-2).each { |i|
        if arr[i] > arr[i+1]
            arr[i], arr[i+1] = arr[i+1], arr[i]
            sorted = false
        end
    }

修复它。