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

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

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.


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