Lesson 15/19

So I put .sort!.reverse! and it completed the course. but I’m not getting the syntax here , can someone please enlighten me. lol, I am not one them people that looks for shortcuts. like explain it to me like I’m 5 lol

Same thing happened to me. I am so stuck!!! :scream:

@bolu001
do you need help on it now or did you get through it?

I assume you’re talking about this syntax:

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

And not the one you used.

We want to sort the object books.

We use the method sort! for this.

The sort! method takes a block, in this block we specify two temporary variables to represent the elements of books, firstBook and secondBook. These will be used by sort! to know in which order it must sort the object.

We use the <=> operator to give the order. If we put the secondBook first (descending order), it means that the greater value will have to come first, if we put firstBook first (ascending order), it means that the lesser value will have to come first.

It’s also explained in the lesson just before this one.

2 Likes

I don’t really understand , if you use the <=> operator you still get the same result as in ascending order.

Just wanted to share that the code in the hint of this problem functions properly, but won’t give you a passing solution unless you use the .sort! method, rather than the .sort (specifically without the ! modifier)

If you want to complete this with one line of code following the format provided by the original code in the editor, try this and think about why it works!

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

Can some1 help me…please I am “lost in space”

Here is my code:

books = [“A Brief History of Time”, “A Wrinkle in Time”]

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

This is what happens when I try to save & submit:

“Oops, try again. It looks like your comparison doesn’t return the correct value (1). Did you remember to compare book_1 <=> book_2 (in that order)?”

Please note my brain is at present turned to soup…I am lost in Translation! Any help would greatly appreciated in advance!

Hi @samg2015

Have you tried using

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

You should pass in the entire array of books. The code is right, just missing books to print out.

I don’t think you need the .reverse on your books.sort! because writing the books in the order that you wrote them makes your code the same as the given line of code…just with a .reverse on it. If you want to go without the .reverse! method, then it’s: books.sort! { |firstBook, secondBook| secondBook <=> firstBook}