ruby-on-railsrubyarrayshash-of-hashes

Ruby hash of array


I have a list of Flights departing and arriving to an airport. Each Flight has a departure/arrival time. I want to display the list of flights as a timeline with the departures on the left and arrivals on the right, grouped by hours, like this:

     Departures  | Arrivals

Hours 08 - 09

Flight 1, 08:15  | Flight ABC, 08:12
Flight 2, 08:21  | Flight XY, 08:36
Flight 05, 08:49 | Flight ABC, 08:38

Hours 09 - 10

Flight 1, 09:25  | Flight ABC, 09:55
Flight 2, 09:56  | 

....

I am creating the hash like this:

@flights= {}

Flight.each do |t|
  @flights[t_time] ||= []
  t_time = t.departure_date.change(min: 0)
  if t.departure
    @flights[t_time][0] << t #departures
  else
    @flights[t_time][1] << t #arrivals
  end
end

This seems to be working. But I have no clue how to parse this structure in the view to access each time, and after that each object in the two arrays.


Solution

  • Finally figured it out. First, I changed the hash and initialized it:

    @global_flights[t_time] ||= {}
    @global_flights[t_time][:departures] ||= [] # departures
    @global_flights[t_time][:arrivals] ||= [] # arrivals
    

    ....

    Flight.each do |t|
        t_time = t.departure_date.change(min: 0)
        if t.departure
            @global_flights[t_time][:departures] << t
        else
            @global_flights[t_time][:arrivals] << t
        end
    end
    

    This allows me in the view to display the data as needed:

    <% @global_flights.each do |times, flights| %>
        <%= times %>
        <% flights[:departures].each do |t| %>
            <%= render partial: "flight", locals: {t: t} %>
        <% end %>
        <% flights[:arrivals].each do |t| %>
            <%= render partial: "flight", locals: {t: t} %>
        <% end %>
    <% end %>