基于散列Ruby内的数组数据将散列拆分成重复的散列?

时间:2015-09-18 15:02:22

标签: ruby-on-rails arrays ruby hash

如何从包含数组字段的单个哈希创建两个或多个新哈希值:

{carStyle: "truck", make: ["Ford","Toyota"], model:["Ranger", "Tacoma"]}

所以我想要两个新的哈希就是这样的:

{carStyle: "truck", make: "Ford", model: "Ranger"}
{carStyle: "truck", make: "Toyota", model: "Tacoma"}

我想知道是否有办法使用地图和收集来实现这一目标?或者,如果有人看到类似的问题,他们可以指出我可能错过了。

提前致谢!

2 个答案:

答案 0 :(得分:1)

data = {carStyle: "truck", make: ["Ford","Toyota"], model:["Ranger", "Tacoma"]}
data[:make].zip(data[:model]).map{|x|
  { carStyle: data[:carStyle], make: x[0], model: x[1] }
}

Mark Reed建议更好的解决方案:

data[:make].zip(data[:model]).map{|x,y|
  { carStyle: data[:carStyle], make: x, model: y }
}

答案 1 :(得分:1)

h = {carStyle: "truck", make: ["Ford","Toyota"], model: ["Ranger", "Tacoma"]}

style, makes, models = h.values_at(:carStyle, :make, :model)
  # => ["truck", ["Ford", "Toyota"], ["Ranger", "Tacoma"]] 

makes.zip(models).map {|make, model| {carStyle: style, make: make, model: model}}
  #=> [{:carStyle=>"truck", :make=>"Ford",   :model=>"Ranger"},
  #    {:carStyle=>"truck", :make=>"Toyota", :model=>"Tacoma"}] 

我添加了局部变量以提高可读性。