Roberto Pezzali Roberto Pezzali - 9 months ago 27
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 { |w| [w.status, []<<] }.to_h

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


if I try with { |w| [w.status, []<<] }

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?


You can try each_with_object:{}){|w, o| (o[w.status] ||= []) <<}

or reduce/inject:{}){|o, w| (o[w.status] ||= []) <<}