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

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

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

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

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 #=> ["melon", "peach", "apple", "orange", "banana"]

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.