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

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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.