Clayton
Clayton

Reputation: 444

Sorting an array in reverse order

I'm going over the logic behind the combined comparison operator and it's ability to reverse the sort order of an array. For example, I could reverse the order of the following array:

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", 
"A Brief History of Time", "A Wrinkle in Time"]

by adding this line of code:

books.sort! { |firstBook, secondBook| secondBook <=> firstBook }

My question is, why would I not be able to just call:

books.reverse!

on this array to get the reverse order?

Upvotes: 0

Views: 2234

Answers (1)

Niklas B.
Niklas B.

Reputation: 95358

reverse just reverses the order of the array, and does not sort it:

irb> arr = [3,1,5]
=> [3, 1, 5]

irb> arr.sort
=> [1, 3, 5]
irb> arr.sort {|x,y| y<=>x}
=> [5, 3, 1]
irb> arr.reverse
=> [5, 1, 3]

But of course you can combine sort and reverse to sort in reverse order:

irb> arr.sort.reverse
=> [5, 3, 1]

Upvotes: 7

Related Questions