Why use combined comparison? 19/19


#1

Hello, I’m confused as to why combined comparison is the preferred approach to this sorting problem…

My first attempt code was simply:

fruits = [“orange”, “apple”, “banana”, “pear”, “grapes”]

fruits.sort!
fruits.reverse!

puts fruits

This worked perfectly and printed my list in the correct order, giving me the same result as the proposed solution. Why is the simple method I used not sufficient? Will it not work in the context of a more complicated program? Please help me understand.


#2

In real world code, simple is better in most instances. However, this is a course and of necessity we need to delve into the crevices and corners to gain exposure to the full range of the language. The combined comparison is not (I don’t think) the preferred approach, only the one in focus from the standpoint of the lesson.

The expected response for the exercise is,

fruits.sort! do |firstFruit, secondFruit|
  secondFruit <=> firstFruit
end

puts fruits

#3

Thanks for the quick response! That makes sense. The exercise didn’t quite bring me to understand the concept at first, but after re-doing a few times it is clear.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.