anon
anon

Reputation:

Ruby/Rails: Convert array of arrays to hash of arrays

I'm looking for an idiomatic way of querying the database and have all the values grouped by column.

For example, the instruction:

@players = Player.pluck(:white, :black, :red, :blue, :yellow)

Returns a multi-dimensional array like this:

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

but I need a hash of arrays like this:

{
  white:  [1, 6, 11],
  black:  [2, 7, 12], 
  red:    [3, 8, 13],
  blue:   [4, 9, 14],
  yellow: [5, 10, 15]
}

Where the first element of all arrays is stored with the 'white' key, the second element of all arrays is stored with the 'black' key and so on.

Upvotes: 3

Views: 1993

Answers (1)

falsetru
falsetru

Reputation: 369454

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
[:white, :black, :red, :blue, :yellow].zip(a.transpose)
# => [[:white, [1, 6, 11]], [:black, [2, 7, 12]], [:red, [3, 8, 13]], [:blue, [4, 9, 14]], [:yellow, [5, 10, 15]]]
Hash[[:white, :black, :red, :blue, :yellow].zip(a.transpose)]
# => {:white=>[1, 6, 11], :black=>[2, 7, 12], :red=>[3, 8, 13], :blue=>[4, 9, 14], :yellow=>[5, 10, 15]}

Upvotes: 8

Related Questions