15. Getting Technical - Why only two variables in the block?



My code does not behave incorrectly. I'd just like come clarification.

books = ["Charlie and the Chocolate Factory", "War and Peace", "Utopia", "A Brief History of Time", "A Wrinkle in Time"]

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

There's 5 book titles but in the sort block there's only two variables; firstBook and secondBook. I don't understand why there's no thirdBook, fourthBook and fifthBook. Can someone please explain? Thanks.


Because the sort method only ever works with two objects at a time. One for the left hand, one for the right. The variables are the placeholders for those two objects and are dynamic.


C  W  U  Ab  Aw
C  W  Ab  U  Aw
   [___]  [___]
C  Ab  W  Aw  U
[___]  [___]
Ab  C  Aw  W  U
    [___]  [___]
Ab  Aw  C  U  W

Seven swaps in all, but only ever two at one time.


The diagram helps make sense of this. Is it correct to say the sort method sorts every possible pair, two at a time, until they are in order?


Integers can be sorted in linear time, but without special knowledge about where-goes-what you'll need to compare.


In a general sense, yes. The actual mechanics may vary depending upon the method. In the example above I started from the left pair, then the next pair.