ppreyer ppreyer - 4 months ago 10
Ruby Question

Sorting an Array in Ruby without using Sort method

I'm trying to use the bubble sort method to sort an array of only three numbers. The code I'm using is below.

def my_sort(list)
return list if list.size <= 1

swapped = false

while !swapped
swapped = false

0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
swapped = true
end
end

list
end

my_sort([3,1,2])


Here is the error message I keep getting:

Syntax error, unexpected $end, expecting keyword_end


I was just wondering which end shouldn't be included?

Answer

You're missing an end after swapped = true. It would be best to indent your code thoroughly and accurately to avoid this kind of problem:

def my_sort(list)
  return list if list.size <= 1 

  swapped = false
  while !swapped
    swapped = false
    0.upto(list.size-2) do |i|
      if list[i] > list[i+1]
        list[i], list[i+1] = list[i+1], list[i]
        swapped = true
      end
    end
  end

  list
end
Comments