Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“natural” sort an array in Ruby

I have an array which contains numbers and alphabets something like:

newArray = ["1 a", "1 b" ,"2 c", "2 a"]

I would like to sort them in a way that the output is expected as follows:

newArray = ["2 a", "2 c" ,"1 a", "1 b"]

What I want to do is sort the numbers in descending order and if the numbers are same, then sort alphabetically

Can I implement a comparison function in sort_by or is there a way to do that using ruby sort

like image 761
blathia Avatar asked Nov 17 '25 22:11

blathia


1 Answers

First you should use a better representation of your input. You can parse your existing array for example like this:

arr = newArray.map { |s| x,y = s.split; [x.to_i, y] }
# => [[1, "a"], [1, "b"], [2, "c"], [2, "a"]]

Then we can sort as we wish using sort_by:

arr.sort_by { |x,y| [-x, y] }
# => [[2, "a"], [2, "c"], [1, "a"], [1, "b"]]
like image 199
Niklas B. Avatar answered Nov 20 '25 14:11

Niklas B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!