FAQ: Methods, Blocks, & Sorting - Sorting

Since you are using the bang operator, you don’t need to assign the results. They mutate the object in place.
So, instead of fruits = fruits.sort! and fruits = fruits.reverse!, you can simply use fruits.sort! and fruits.reverse!
If you omit the bang operator, then you will need to do assignments e.g. fruits = fruits.sort
If you want to simply sort an array of strings in reverse order, then your approach is all that is needed. You don’t need to bother with elsiif statements or the <=> operator.
I have shared my thoughts on how we are being introduced to the <=> operator, so that we can gradually tackle more complex sorting logic with our own custom code. I have shared my thoughts in this post. It is just my opinion and I may well be wrong.

1 Like