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.
CodePudding user response:
You can do it with:
collected_slots.sort! { |a,b| a <=> b }
"Comparisons for the sort will be done using the <=> operator or using an optional code block.
The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b.
The result is not guaranteed to be stable. When the comparison of two elements returns 0, the order of the elements is unpredictable. "
Also keep in mind the !
at the end of .sort
will mutate the original array. If you don't want to mutate you can do:
sorted_slots = collected_slots.sort { |a,b| a <=> b }
then you just use a slice to display the ranges:
sorted_slots.each_slice(2) do |a,b|
puts "#{a}-#{b}"
end
CodePudding user response:
I think this should do what you want.
- Sort the entries after converting each entry to a DateTime object.
- 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"]