Roberto Pezzali Roberto Pezzali - 4 months ago 7
Ruby Question

Ruby: Map array to hash creating an array inside the hash

I'm creating a simple analytic chart and to avoid heavy query in realtime I need to save a cached result dataset in a table dedicated to these statistics.

Any user try some course, and I want to save the ids of the course using a status. So something like

{ "invited": [1,3,6], "done": [2,9] }


I write this function

u.courses.map { |w| [w.status, []<<w.id] }.to_h


but of course every iteration my array is initialized so I have

{"invited"=>[5101]}


if I try with

u.courses.map { |w| [w.status, []<<w.id] }


I obtain

[["invited", [1]], ["invited", [748]], ["invited", [1445]], ["invited", [2113]], ["invited", [2833]], ["invited", [6017]], ["invited", [4146]], ["invited", [5101]]]


How can I create the array on the first iteration keeping it inside my map?

Answer

You can try each_with_object:

u.courses.each_with_object({}){|w, o| (o[w.status] ||= []) << w.id}

or reduce/inject:

u.courses.reduce({}){|o, w| (o[w.status] ||= []) << w.id}
Comments