Bubble sort in ruby

Your overall assessment is correct. This is a bit confusing because, as you quite perceptively pointed out, sorted is set to false immediately as the function begins. The reason for this, however, is that the logic contained in times (which is also a ‘loop’ construct; a Ruby ‘block’) will assert sorted to false while (in the English sense) there was a need to switch values (e.g. sort).
In other words, once the operation has traversed the entire array AND there was no longer a need to make a swap in order to “bubble” a lower value before its higher brethren the sort is finished.
Without that flag the loop would be infinite; even after there are no more values that need to be rearranged.
Think of the value sorted as “Was a sort operation performed?” and its inverse as “No more work needs to be done; we are sorted”

Put another way:
Each time the execution reaches the end of the until the value of sorted will only be true a swap of values was not necessary in that iteration.
[Re]setting it to true at the beginning of the loop ensures the flag will be useful.

This is why recursive functions are difficult to grasp.


This is taking advantage of [one of] the many shortcuts in the Ruby language that has made it very popular among developers. In Ruby you can make multiple assignments on a single line.

val_one, val_two, val_three = 1, 2, 3

This will result in val_one containing 1, val_two containing 2 and val_three containing 3

You are correct that commas, used in this way, are unusual in most programming languages.