codedude
codedude

Reputation: 6549

Sort an array of string in descending order

Say I want to sort an array of strings in Ruby in descending order. So for example:

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

I'm currently going through Code Academy's Ruby course and they say to use the following code to achieve this:

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

However, couldn't this also be done by simply writing the following?

books.sort!.reverse

They both produce the same result on the Code Academy lesson but I was wondering if there what the difference was between the two.

Upvotes: 1

Views: 7387

Answers (3)

Imanol Alvarez
Imanol Alvarez

Reputation: 1

try with these options:

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

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

3. books.sort_by{ |Book| Book}.reverse

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

There is a slight performance difference between the two

This one is just one step of sort

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

This one actually contains two steps: sort and reverse

books.sort!.reverse

So, when the data is large the first one is preferred. However, in normal cases the second one would be simpler to write and the slight difference on performance doesn't matter that much.

Upvotes: 4

Anurag Soni
Anurag Soni

Reputation: 161

I think that the tutorial was just trying to help you understand the <=> (spaceship operator) and how sorting is affected by the order of the variables. books.sort!.reverse is something that you would use more commonly.

Upvotes: 1

Related Questions