Methods, Blocks, & Sorting 5/19
I'm having a hard time understanding how this code works. Although I can pass the exercise, I want to know what is actually happening before I move forward.
From my understanding:
fruits.sort! simply sorts the elements in the array in ascending order. We can modify the way it works by doing things like:
fruits.sort! do |firstfruit, secondfruit|
followed by code to compare the two fruits.
I was really curious about how it grabbed "firstFruit" and "secondFruit" out of the array so I made the code shown below.
I was expecting firstFruit to be "Orange" while the secondFruit to be "apple", but instead secondFruit was "Banana". Why is that? I thought it would grab "apple" since it's the 2nd element in the array.
Input: fruits = ["orange", "apple", "banana", "pear", "grapes"] fruits.sort! do |firstFruit, secondFruit| puts firstFruit puts secondFruit end Output: orange banana