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.

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Ok. I guess that makes sense. I thought perhaps this was bad form or not allowed. Thanks!
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.
I'm actually going through a couple web sites right now. I'll take a look at your suggestions
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

2 Comments

You should not digging an old post (with accepted answer), without answering the question (which was about the difference between the two command).
Sorry you're right, I just wanted to help. Regards!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.