Home
Map
sort Examples: ArraysUse the sort method. Sort with blocks, sort in descending order and sort in-place.
Ruby
This page was last reviewed on Feb 1, 2024.
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.
Array
We use ascending (low to high) and descending sort orders. We handle strings, numbers, and even classes. We sort based on anything.
String array. 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 1 With no exclamation mark, we create a sorted copy of the array. Both are independent in memory.
Part 2 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.
values = ["z", "a", "b"] # Part 1: call sort on array, which returns a new array. copy = values.sort puts copy.to_s # Part 2: Call sort!, which changes the array in-place. values.sort! puts values.to_s
["a", "b", "z"] ["a", "b", "z"]
Block. 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 an 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. values = ["short", "minuscule", "tiny"] # Sort from shortest to longest. result = values.sort {|left, right| left.length <=> right.length} puts result
tiny short minuscule
Descending. 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. numbers = [1, 200, 900, 300, 1000, 5] # Sort from highest to lowest (descending). numbers.sort! {|x, y| y <=> x} puts numbers
1000 900 300 200 5 1
Reverse. 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.
reverse
Tip As with sort, we can reverse an array in-place by using the method with the trailing exclamation mark.
# Contains letters: nmxe. letters = ["n", "m", "x", "e"] # Reverse the letters and store in a copy. copy = letters.reverse puts copy.join # Reverse the letters in-place. letters.reverse! puts letters.join
exmn exmn
Class. 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.
class
Start We create three Cube instances and add them to an array. The push() method on array appends to end of the array.
Info Each class instance has a different value for its volume. They are not added in a sorted order.
Then We invoke the sort method. In the block, we compare the volume for each Cube instance, ordering them from low to high.
class Cube def initialize(volume) @volume = volume end # This property returns the volume. def volume @volume end # Get string representation. def to_s "Volume = #@volume" end end # Fill array with three cubes. array = [] array.push Cube.new(10) array.push Cube.new(15) array.push Cube.new(5) # Sort array in-place by Cube volume. array.sort! {|x, y| x.volume <=> y.volume} puts array
Volume = 5 Volume = 10 Volume = 15
String. 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.
Detail The sort_string method relies on the split method. With an empty string delimiter, it separates the characters.
String split
def sort_string(value) # Convert string into array of characters. array = value.split "" # Sort the characters. array.sort! # Join the characters into a new string. result = array.join return result end puts(sort_string("rat"))
art
Hash. 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.
Hash
A summary. In many cases, we can use the default sort or "sort!" methods. But to sort objects, or sort based on aspects of values, we require special comparisons.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 1, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.