ruby解析数组到哈希

时间:2012-06-25 07:37:29

标签: ruby arrays parsing hash

这样的数组:

a = ["<root>", 
"<products>", 
"<product>", 
"<id>", "1", "</id>",
"<name>", "name1", "</name>", 
"</product>",
"<product>", 
"<id>", "2", "</id>",
"<name>", "name2", "</name>", 
"</product>",
"</products>", 
"</root>"]

和这样的哈希:

b = {
"products" => {
  "product" => [
     {"id" => "1", "name" => "name1"},
     {"id" => "2", "name" => "name2"}
   ]
  }
}

如何从ca中获取此哈希b

c = {
"products" => {
  "product" => [
     {"id" => "1", "name" => "name1", "id_index" => 4, "name_index" => 7},
     {"id" => "2", "name" => "name2", "id_index" => 12, "name_index" => 15}
   ]
  }
}

4,7,12,15是数组a中的“1”,“name1”,“2”,“name2”的索引。

1 个答案:

答案 0 :(得分:0)

我猜它会是这样的:

c = {'products' => {'product' => b['products']['product']
  .map{|o| o.merge({'id_index' => a.index(o['id']), 'name_index' => a.index("name#{o['id']}")})}}}