How to Sort a Ruby Array in Descending Order Based on Length of Each Element?

Sorting Ruby array elements with longest length first and the shortest length last

To sort array elements with the longest length first and the shortest length last (i.e. in descending order), you can use the Array#sort method in the following way:

fruits = ["orange", "melon", "peach", "apple", "banana"]
sortedFruits = fruits.sort { | a, b | b.length - a.length }

print sortedFruits #=> ["orange", "banana", "melon", "peach", "apple"]

This would sort the strings of the same length according to the order in which they appear in the original array.

As an alternative, you may achieve the same result using the Array#sort_by method like so:

fruits = ["orange", "melon", "peach", "apple", "banana"]
sortedFruits = fruits.sort_by { | fruit | -fruit.length }

print sortedFruits #=> ["orange", "banana", "melon", "peach", "apple"]
print fruits

Both, Array#sort and Array#sort_by, return a new array with the sorted elements.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.