I want to collect my users' data as an array:h = {}a = [[user_3, 765], [user_1, 2], [user_1, 1], [user_2, 124],[user_1, 3], [user_2, 223], [user_2, 334]]# Expected output :: {user_3=>[765], user_1=>[2, 1, 3], user_2=>[124, 223, 334]} a.each do |x|  if h.keys.include?(x.first)    h[x.first] = (h[x.first] << x.last)  else    h[x.first] = [x.last]  endendEverything is working fine in my Ruby script, but is there any better way to achieve my result?
Collecting users' data as an array
performance;ruby;ruby on rails
You very rarely need to modify a variable from inside an each block.Instead, check out all the methods available to you in Array and Enumerable.Among them, there's #each_with_objects, which you can use like so:a.each_with_object({}) do |(name, id), hash|  hash[name] ||= []  hash[name] << idendwhich'll produce the same hash as your current code.You could also do:a.group_by(&:first).map do |name, pairs|  [name, pairs.map(&:last)]endThat returns an array of arrays, but you can turn that into a Hash with Hash[]. You may not need to, though. A lot of things treat an Array object with [key, value]-style elements the same as a Hash object. Depends on your needs.