Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a Ruby array of strings by length?

How do I sort this:

arr = ["aaa","aa","aaaa","a","aaaaa"]; 

Into this?

arr = ["a","aa","aaa","aaaa","aaaaa"]; 
like image 999
Dr. Frankenstein Avatar asked Jul 03 '10 17:07

Dr. Frankenstein


People also ask

How do you sort an array by string length?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How can you sort an array Ruby?

The Ruby sort method works by comparing elements of a collection using their <=> operator (more about that in a second), using the quicksort algorithm. You can also pass it an optional block if you want to do some custom sorting. The block receives two parameters for you to specify how they should be compared.


1 Answers

arr = arr.sort_by {|x| x.length} 

Or in 1.8.7+:

arr = arr.sort_by(&:length) 
like image 184
sepp2k Avatar answered Oct 04 '22 04:10

sepp2k