我们有以下数据结构:

{:a => ["val1", "val2"], :b => ["valb1", "valb2"], ...}

我想把它变成
[{:a => "val1", :b => "valb1"}, {:a => "val2", :b => "valb2"}, ...]

然后回到第一种状态。有人有好看的设备吗?

最佳答案

此解决方案适用于任意数量的值(val1、val2…valn):

{:a => ["val1", "val2"], :b => ["valb1", "valb2"]}.inject([]){|a, (k,vs)|
  vs.each_with_index{|v,i| (a[i] ||= {})[k] = v}
  a
}
# => [{:a=>"val1", :b=>"valb1"}, {:a=>"val2", :b=>"valb2"}]

[{:a=>"val1", :b=>"valb1"}, {:a=>"val2", :b=>"valb2"}].inject({}){|a, h|
  h.each_pair{|k,v| (a[k] ||= []) << v}
  a
}
# => {:a=>["val1", "val2"], :b=>["valb1", "valb2"]}

关于ruby - 在Ruby中将哈希数组转换为哈希数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1640979/

10-12 16:24