Reputation: 6549
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
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
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
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