ryanpitts1
ryanpitts1

Reputation: 894

Sort numbers with colons

I have a list of Bible verses, times, or some other strings with numbers and colons. I would like those sorted into this:

1:5
2:1
2:8
2:14
11:36

How would I sort those numbers?

I assume I have to parse the string, separate on colon, and then sort. What I tried gives me things like this:

1:5
11:36
2:1
2:14
2:8

Upvotes: 3

Views: 209

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

arr = %w| 1:5 11:36 2:1 2:14 2:8 |
  #=> ["1:5", "11:36", "2:1", "2:14", "2:8"]

arr.sort_by { |s| Gem::Version.new(s.tr(':', '.')) }
  #=> ["1:5", "2:1", "2:8", "2:14", "11:36"]

See Enumerable#sort_by, String#tr and Gem::Version::new. The latter is part of the standard Ruby library.

Upvotes: 6

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Use Enumerable#sort_by

input = %w|1:5 11:36 2:1 2:14 2:8|
input.sort_by { |e| e.split(':').map(&:to_i) }
#⇒ ["1:5", "2:1", "2:8", "2:14", "11:36"]

map(&:to_i) part is needed to make integers out of strings, because 11 > 2 but "11" < "2".

Upvotes: 9

Related Questions