Need Code explaination!


#1
# To sort our books in ascending order, in-place
 
 books.sort! { |firstBook, secondBook| firstBook <=> secondBook }

Can someone please help me explain this code ?


#2

We use the sort! method on books, and we specify to sort which method of sorting we want.

Everything is explained in 14/19:

We can also use a new operator called the combined comparison operator to compare two Ruby objects. The combined comparison operator looks like this: <=>. It returns 0 if the first operand (item to be compared) equals the second, 1 if first operand is greater than the second, and -1 if the first operand is less than the second.

A block that is passed into the sort method must return either 1, 0, -1. It should return -1 if the first block parameter should come before the second, 1 if vice versa, and 0 if they are of equal weight, meaning one does not come before the other (i.e. if two values are equal).

So if firstBook <=> secondBook returns 1 on the first comparison, then the two elements will be switched because then the sort method will get 1 in the block of code and interpret it as such.

If it's not clear enough I can give examples.


#3

Also note - your code is just doing what sort already does - sorting the books in an ascending order. you could just say books.sort and get the same result. You are essentially passing a block to sort and telling it to use your sorting method instead of the default method. This may become clearer when you need to reverse the order of the sorting:

books.sort!{|item1, item2| item2 <=> item1}

One line tells it to sort in the order you want the array to be in. Otherwise you could also do it with two lines:

books.sort! #puts the order of the books in ascending, alphabetical order
books.reverse! #reverses the order of the items in the array