简体   繁体   English

Ruby / Rails:将数组数组转换为数组的哈希值

[英]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. 如果所有数组的第一个元素都使用'white'键存储,则所有数组的第二个元素都存储为'black'键,依此类推。

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]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM