Ruby Sort ArraysUse the sort method. Sort with blocks, sort in descending order and sort in-place.
dot net perls
Sort. Things do not come sorted. Often we must arrange them ourselves. Fortunately Ruby offers the sort method, available on arrays. It can be customized with blocks for extra power.
Sort notes. We use ascending (low to high) and descending sort orders. We handle strings, numbers, and even classes. We sort based on anything.
This program creates a string array with 3 characters in it. They are in no particular order. We then invoke the sort method, which alphabetizes those strings.
Part A With no exclamation mark, we create a sorted copy of the array. Both are independent in memory.
Part B Next "sort!" reorders the array in-place. Methods that end in an exclamation mark operate in-place.
Info Sort requires no arguments. By default, it orders in ascending order, from low to high.
Ruby program that uses sort
values = ["z"
# Part A: call sort on array, which returns a new array.
copy = values.sort
# Part B: Call sort!, which changes the array in-place.
["a", "b", "z"]
["a", "b", "z"]
Sort() can be called with a block. We use the curly brackets to specify the block of code. We first specify, on the left between vertical bars, the arguments.
And We use the <=> operator to compare the two arguments in the block. Here we compare the string lengths, not the strings themselves.
# Has three strings of different lengths.
Ruby program that uses block to sort
values = ["short"
# Sort from shortest to longest.
result = values.sort
left.length <=> right.length}
A descending sort orders the elements from high to low. By default, the sort method works in an ascending order (as from A to Z).
Tip With descending, we must specify a block of code that compares the elements in the opposite order.
So When sort receives X and Y, we compare Y to X. This inverts the resulting order. And we have a descending sort.
# Contains six different numbers.
Ruby program that uses descending sort order
numbers = [1, 200, 900, 300, 1000, 5]
# Sort from highest to lowest (descending).
y <=> x}
Reversing is not sorting. With reverse(), we simply change the existing order. We do not sort or reorder the elements in any other way. We merely invert the existing order.
Tip As with sort, we can reverse an array in-place by using the method with the trailing exclamation mark.
# Contains letters: nmxe.
Ruby program that reverses arrays
letters = ["n"
# Reverse the letters and store in a copy.
copy = letters.reverse
# Reverse the letters in-place.
This example adds more complexity. We introduce a class called Cube. It has a simple initialize method. And it has a volume property and a to_s method, which outputs a string.
First We create three Cube instances and add them to an array. The push() method on array appends to end of the array.
Volume Each class instance has a different value for its volume. They are not added in a sorted order.
Sort We then invoke the sort method. In the block, we compare the volume for each Cube instance, ordering them from low to high.
Ruby program that sorts classes in array
@volume = volume
# This property returns the volume.
# Get string representation.
"Volume = #@volume"
# Fill array with three cubes.
array = 
# Sort array in-place by Cube volume.
x.volume <=> y.volume}
Volume = 5
Volume = 10
Volume = 15
To sort a string, we must first convert it into characters with split(). Then we join those characters back together into a string. We implement a sort_string() method.
Split The sort_string method relies on the split method. With an empty string delimiter, it separates the characters.
Ruby program that sorts characters in string
# Convert string into array of characters.
array = value.split ""
# Sort the characters.
# Join the characters into a new string.
result = array.join
A Hash too has a sort method. But internally, this method copies the hash's data into an array of pairs. We can then sort that array of pairs by key or value.
A summary. Advanced sorting requires knowledge of the block syntax in Ruby. In many cases, we simply use the default sort or "sort!" methods.
But to sort objects, or sort based on aspects of values, we require special comparisons. Sorting can become complex. And often, keeping things sorted instead is faster.
© 2007-2021 sam allen. send bug reports to email@example.com.