2

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?

1
  • Please read "minimal reproducible example". We need the minimal code that demonstrates the problem, the associated minimum input and your expected output. We don't know what u is, nor courses. We can guess but we shouldn't have to, you should show us. Commented Jul 14, 2016 at 23:24

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

Comments

0
u.course.each_with_object({}) { |course, h|
  h.update(course.status=>[course.id]) { |_,o,n| o+n } }

This uses the form of Hash#update (aka merge!) that employs a block ({ |_,o,n| o+n }) to determine the values of keys that are present in both hashes being merged. The first block variable is the common key. Since that's not used in the block calculation, I've represented it with an underscore, which is common practice. See the doc for update for an explanation of the other two block variables.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.