1

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.

codedude
  • 6,244
  • 14
  • 63
  • 99
  • Possible duplicate of [Sorting an array in descending order in Ruby](https://stackoverflow.com/questions/2642182/sorting-an-array-in-descending-order-in-ruby) – Jon Schneider Mar 14 '19 at 18:19

3 Answers3

4

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.

Billy Chan
  • 24,625
  • 4
  • 52
  • 68
1

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.

Anurag Soni
  • 161
  • 1
  • 7
  • Ok. I guess that makes sense. I thought perhaps this was bad form or not allowed. Thanks! – codedude Jun 23 '14 at 02:04
  • 1
    You might like codeschool's tryruby.org or 'learn ruby the hard way' if you liked the ruby course on codeacademy. I found those to be a better starter's course for ruby with more explanations about the way things work. – Anurag Soni Jun 23 '14 at 02:07
  • I'm actually going through a couple web sites right now. I'll take a look at your suggestions – codedude Jun 23 '14 at 02:12
0

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