如何从数组哈希中获取哈希数组

How to get an array of hashes from a hash of arrays

我一直在思考ruby下一个操作如何进行,但我是新手,我无法得到解决方案。

我有一个数组散列:
{text: ['1','2'], position: [1,2]}
我想要:
[{text: '1', position: 1},{text: '2', position: 2}]

希望你能帮助我。
谢谢

获取键(:text:positions)和值(数组):

h = {text: ['1','2'], position: [1,2]}
keys, values = h.to_a.transpose
# keys => [:text, :position]
# values => [["1", "2"], [1, 2]]

然后,使用Array#transpose / Array#zip得到你想要的:

# values.transpose => [["1", 1], ["2", 2]]
values.transpose.map {|vs| keys.zip(vs).to_h }
# => [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]

# values.transpose.map {|vs| Hash[keys.zip(vs)] }
#   ^ Use this if `to_h` is not available.

使用 #zip :

hash = {text: ['1','2'], position: [1,2]}
output = []
hash[:text].zip(hash[:position]) do |a1, a2| 
  output << {text: a1, position: a2}
end
output # => [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]

另一种方式:

h = {text: ['1','2'], position: [1,2]}

h.map { |k,v| [k].product(v) }.transpose.map(&:to_h)
  #=> [{:text=>"1", :position=>1}, {:text=>"2", :position=>2}]