Search⌘ K
AI Features

Solution: Number Sorting

Explore how to sort numbers by using Ruby's each_with_index method to access array elements and their indexes. Understand how to compare elements within the array to sort them effectively in this practical coding solution.

We'll cover the following...

Solution

Ruby
array = [10, 8, 7, 3, 4, 5, 9, 1, 2, 6]
array.each_with_index do |num, idx|
# comparing No.idx with remaining ones
(idx+1..array.size() - 1).each do |idx2|
if array[idx] > array[idx2]
# swap
array[idx], array[idx2] = array[idx2], array[idx]
end
end
end
puts "The numbers in order: #{array.join(', ')}"

Explanation

  • Line 2: The ...