Collecting users' data as an array 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"=&gt;[765], "user_1"=&gt;[2, 1, 3], "user_2"=&gt;[124, 223, 334]} 
a.each do |x|
  if h.keys.include?(x.first)
    h[x.first] = (h[x.first] &lt;&lt; x.last)
  else
    h[x.first] = [x.last]
  end
end


Everything is working fine in my Ruby script, but is there any better way to achieve my result?
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] &lt;&lt; id
end


which'll produce the same hash as your current code.

You could also do:

a.group_by(&amp;:first).map do |name, pairs|
  [name, pairs.map(&amp;:last)]
end


That 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.