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
arrayThis 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.
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"]
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.
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 resulttiny short minuscule
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).
# Contains six different numbers. numbers = [1, 200, 900, 300, 1000, 5] # Sort from highest to lowest (descending). numbers.sort! {|x, y| y <=> x} puts numbers1000 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.
# 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.joinexmn 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
.
push()
method on array appends to end of the array.class
instance has a different value for its volume. They are not added in a sorted order.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 arrayVolume = 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.
sort_string
method relies on the split method. With an empty string
delimiter, it separates the characters.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
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.
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.