<< Back to RUBY
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.
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 = ["x", "c", "m"]
# Part A: call sort on array, which returns a new array.
copy = values.sort
puts copy.to_s
# Part B: 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.
ClassFirst: 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.
SplitRuby 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.
Related Links:
- Ruby Convert Types: Arrays and Strings
- Ruby File Handling: File and IO Classes
- Ruby Regexp Match Method
- Ruby String Array Examples
- Ruby include: Array Contains Method
- Ruby Class Examples: Self, Super and Module
- Ruby DateTime Examples: require date
- Ruby 2D Array Examples
- Ruby Number Examples: Integer, Float, zero and eql
- Ruby Exception Examples: Begin and Rescue
- Top 65 Ruby Interview Questions (2021)
- Ruby on Rails Interview Questions (2021)
- Ruby String Examples (each char, each line)
- Ruby if Examples: elsif, else and unless
- Ruby Math Examples: floor, ceil, round and truncate
- Ruby Sub, gsub: Replace String
- Ruby Substring Examples
- Ruby Console: Puts, Print and stdin
- Ruby Remove Duplicates From Array
- Ruby Random Number Generator: rand, srand
- Ruby Recursion Example
- Ruby ROT13 Method
- Ruby Iterator: times, step Loops
- Ruby String Length, For Loop Over Chars
- Ruby Join Example (Convert Array to String)
- Ruby Format String Examples
- Ruby Copy Array Example
- Ruby Keywords
- Ruby Nil Value Examples: NoMethodError
- Learn Ruby Tutorial
- Ruby Method: Def, Arguments and Return Values
- Ruby Fibonacci Sequence Example
- Ruby Hash Examples
- Ruby While, Until and For Loop Examples
- Learn Ruby on Rails Tutorial
- Ruby Word Count: Split Method
- Ruby Sort Arrays (Use Block Syntax)
- Ruby Case Examples: Ranges, Strings and Regexp
- Ruby Array Examples
- Ruby Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf