Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an Array of Strings by their Integer Values

Let's say I have an unsorted array from 1 to 10, as shown below...

a = ["3", "5", "8", "4", "1", "2", "9", "10", "7", "6"]

If I use the sort method on this array, it returns this...

a.sort = ["1", "10", "2", "3", "4", "5", "6", "7", "8", "9"]

As you can see, the 10, appears before the 2, which is incorrect. How can I sort these numbers so that 10 appears correctly?

EDIT: Thank you all for your responses. I should explain my problem a little better. The array I need sorted is for an e-commerce price list. So the array appears as follows...

a = ["0-10", "11-20", "21-30", "31-40" etc.]

So the strings cannot be converted to integers. I should have put this when I wrote the question. I did not think that there would be much difference in the fix. My mistake, I apologise for making this assumption! How though can I sort this array? Thanks!

like image 293
tob88 Avatar asked Sep 07 '25 15:09

tob88


2 Answers

I'll throw another method out there since it's the shortest way I can think of

a.sort_by(&:to_i)
like image 85
Wizard of Ogz Avatar answered Sep 09 '25 12:09

Wizard of Ogz


As your updated question states:

array.sort_by {|elt| ary = elt.split("-").map(&:to_i); ary[0] + ary[1]}

even geekier:

array.sort_by {|elt| ary = elt.split("-").map(&:to_i).inject(&:+)}
like image 37
apneadiving Avatar answered Sep 09 '25 11:09

apneadiving