Sort numbers with colons

  • A+
Category:Languages

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 

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: