How do I sort this:
arr = ["aaa","aa","aaaa","a","aaaaa"];
Into this?
arr = ["a","aa","aaa","aaaa","aaaaa"];
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.
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.
arr = arr.sort_by {|x| x.length}
Or in 1.8.7+:
arr = arr.sort_by(&:length)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With