Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting range values

Tags:

sorting

ruby

I want to sort an array of strings representing numerical ranges like the following:

b = ["0-5", "100-250", "5-25", "50-100", "250-500", "25-50"]

Using the sort method I get:

b.sort 
# => ["0-5", "100-250", "25-50", "250-500", "5-25", "50-100"]

I want it like this instead:

["0-5, "5-25", "25-50", "50-100", "100-250", "250-500"]
like image 206
Kanna Avatar asked Apr 08 '14 11:04

Kanna


1 Answers

Try:

b.sort_by { |r| r.split('-').map(&:to_i) }
# => ["0-5", "5-25", "25-50", "50-100", "100-250", "250-500"] 

This solution takes each item ("0-5") splits it to two items (["0", "5"]), and converts them to integers ([0, 5]). Now sort sorts by the array (first item first, and the second as a tie-breaker).

like image 157
Uri Agassi Avatar answered Nov 15 '22 21:11

Uri Agassi