8

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"]
1
  • 2
    Have you tried converting those strings to actual ranges and sort those? Commented Apr 8, 2014 at 11:31

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

Comments

5
b.sort_by { |a| a.split('-').first.to_i }

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

Comments

5
b.sort_by(&:to_i)
  #=> ["0-5", "5-25", "25-50", "50-100", "100-250", "250-500"]

because

"25-50".to_i #=> 25

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.