Joey Li Joey Li - 20 days ago 7
Ruby Question

How does this while loop evaluate the condition to be true or false?

I created the following code to do the bubble sort and the code worked out fine. My question is why it worked... When the method is called, I assume the computer will first evaluate whether $x is equal to 0. But I haven't assigned value to $x to begin with, so what makes the computer start to run the each loop?

It seems to have something to do with the fact that x is a global variable, but I am not sure how. Please suggest!

def bubble_sort(arr)
while $x != 0
$x = 0
arr.each_with_index do |i, j|
if arr[j+1] != nil && i > arr[j+1]
arr[j], arr[j+1] = arr[j+1], arr[j]
$x += 1
end
end
end
arr
end

p bubble_sort([4,3,78,2,0,5,100,34])

Answer

I assume you're invoking the method only once? ...

The global $x doesn't exist during the first call and the search for that global variable returns nil.

Hence, the first while loop evaluates $x==0 as nil == 0 which is false.