How to sort an an array having mulitple time slots

Viewed 57

I have an array collected_slots = ["09:30", "09:45", "09:40", "09:55", "09:35", "09:50"]

I have to sort it on the bases of the time, I have tried

sorted_slots = collected_slots.sort_by do |slot|
parsed = collected_slots[:time].split('-').first
[parsed&.to_i, parsed.split(':').second&.to_i]

but it doesn't work

What I want is collected_slots = ["09:30-09:35", "09:35-09:40", "09:40-09:45", "09:45-09:50", "09:50-09:55"]

I have tried but it doesn't works. Please help me with this.

1 Answers

I think this should do what you want.

  1. Sort the entries after converting each entry to a DateTime object.
  2. map the index, except the last index, of each entry to the value at that index and the value at the next index
require 'date'
input = ["09:30", "09:45", "09:40", "09:55", "09:35", "09:50"]
sorted = input.sort_by {DateTime.parse(_1)}
output = sorted[0...-1].each_index.map {"#{sorted[_1]}-#{sorted[_1+1]}"}
=> ["09:30-09:35", "09:35-09:40", "09:40-09:45", "09:45-09:50", "09:50-09:55"] 
Related