3

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.

1 Answer 1

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

Comments

Your Answer

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