0

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?

3
  • 1
    Question is not clear. Commented Mar 25, 2014 at 15:33
  • 2
    "why would I not be able to just call" You are able to do that. What is your question? Commented Mar 25, 2014 at 15:33
  • I think I was just more confused as to why .reverse wouldn't sort the array in reverse order. Commented Mar 25, 2014 at 16:18

1 Answer 1

7

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I find it weird that sort doesn't have an argument that does that

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.