matski matski - 1 month ago 14
JSON Question

Ruby: build hash by mapping arrays to an array

I have a dates array containing 31 items (shortened here for clarity)

Tuesday 8, November
Wednesday 9, November
#etc.


and a movies hash containing 31 items, each containing movie names and showtimes (shortened here for clarity)

{:movie=>"The Neon Demon", :time=>"4:15 PM"}
{:movie=>"Breaking a Monster", :time=>"6:45 PM"}
{:movie=>"The Citizen", :time=>"9:00 PM"}


I am trying to build a hash for json output which has this structure

[
{
"Tuesday 8, November": {
"movies": [
{
"movie": "The Neon Demon",
"time": "4:15 PM"
},
{
"movie": "Breaking a Monster",
"time": "6:45 PM"
},
{
"movie": "The Citizen",
"time": "9:00 PM"
}
]
},
{
"Wednesday 9, November": {
"movies": [
{
"movie": "The First Monday in May",
"time": "4:15 PM"
},
{
"movie": "The Neon Demon",
"time": "6:30 PM"
},
{
"movie": "Breaking a Monster",
"time": "9:00 PM"
}
]
}, #etc
}
]


Right now I'm using

Output = []
Output << { dates => { movies: movies }}
puts JSON.pretty_generate Output


But its not arranging elements correctly and I can't figure out the best way to do it. Can anyone give me a tip on how to do it correctly? Thanks

Answer

You're really just one call to zip away from a solution:

movies = [
  {:movie=>"The Neon Demon", :time=>"4:15 PM"},
  {:movie=>"Breaking a Monster", :time=>"6:45 PM"},
  {:movie=>"The Citizen", :time=>"9:00 PM"}
]

dates = [
  'Tuesday 8, November',
  'Wednesday 9, November',
  'Thursday 10, November'
]

dates.zip(movies).to_h
# => {"Tuesday 8, November"=>{:movie=>"The Neon Demon", :time=>"4:15 PM"}, ... }

As a note date formats like that are extremely annoying from a programming perspective since they can't be sorted and are language specific. ISO date format like 2016-11-08 works a lot better in practice.