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"]
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).
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