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


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-ET4bU/3/4?curriculum_id=5059f8619189a5000201fbcb


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.


#2

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.

Imagine,

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.


#3

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?


#4

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


#5

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.


#7