Good day. I have an array

[[6, 17], [3, 18], [6, 18], [3, 19], [6, 19],....] 

like using ruby, convert it to

 {3 => [18,19], 6=>[17,18,19],......} 

    1 answer 1

    You can use the inject iterator, passing it a hash with a default key value equal to the new array (in the block below, the hash is denoted by m )

     arr = [[6, 17], [3, 18], [6, 18], [3, 19], [6, 19]] res = arr.inject(Hash.new { |h, k| h[k] = [] }) do |m, a| m[a.first] << a.last m end p res # {6=>[17, 18, 19], 3=>[18, 19]} 

    Or, even better, use the iterator each_with_object , which allows you to fit one line in a block

     arr = [[6, 17], [3, 18], [6, 18], [3, 19], [6, 19]] res = arr.each_with_object(Hash.new { |h, k| h[k] = [] }) { |a, m| m[a.first] << a.last } p res # {6=>[17, 18, 19], 3=>[18, 19]} 

    Here, the object also acts as a hash, to whose elements the array Hash.new { |h, k| h[k] = [] } Hash.new { |h, k| h[k] = [] } .