HomeSearch

Ruby Sort Arrays (Use Block Syntax)

Use the sort method. Sort with blocks, sort in descending order and sort in-place.
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.
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.

And: With no exclamation mark, we create a sorted copy of the array. Both are independent in memory.

In-place: Then, "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 = ["x", "c", "m"] # Call sort on array, which returns a new array. copy = values.sort puts copy.to_s # Call sort!, which changes the array in-place. values.sort! puts values.to_s Output ["c", "m", "x"] ["c", "m", "x"]
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 the <=> operator to compare the two arguments in the block. Here we compare the string lengths, not the strings themselves.

Ruby program that uses block to sort # 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 Output 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.

Ruby program that uses descending sort order # 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 Output 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.

Tip: As with sort, we can reverse an array in-place by using the method with the trailing exclamation mark.

Ruby program that reverses arrays # 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 Output 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

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 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 Output 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.

Split: The sort_string method relies on the split method. With an empty string delimiter, it separates the characters.

Split
Ruby program that sorts characters in string 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")) Output 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: sort
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-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls