Ruby On Rails:将字符串中的路径转换为递归哈希

时间:2012-07-13 11:26:05

标签: ruby-on-rails ruby string hash path

有人能建议我这样做的方法吗? (所有都在主题中:D)

我想要的是使用“路径”并将其转换为一个子键,

e.g。 :我有那个参数:path =“earth / animal / human / men / young /”value =“martin”           我想要:

  `Global_hash = { earth => { human => { men => { young => "martin"
                                                }
                                       }
                            }
                 }`

path =“earth / animal / human / men / old /”value =“John”   我想要:

 Global_hash = { earth => { human => { men => { young => "martin",
                                                old   =>  "John" 
                                         }
                                }
                     }
          }

添加其他

path =“earth / animal / human / women / old /”value =“Eve”   我想要:

`Global_hash = { earth => { human => { men   => { young => "martin",
                                                  old      =>  "John"
                                                },
                                       women => { old => "Eve"
                                                }
                                     }
                          }
               }

`

最终目标是使用2个参数生成yml文件的方法: 路径和价值

例子产生: `

earth:
  animal:
    human:
      men:    
        young: "martin"
        old: "John"
      women:
        old: "Eve"

` 它将允许我们有一个yml文件,所有对象都按部分排序,这要归功于它们的路径。

先谢谢

2 个答案:

答案 0 :(得分:5)

path = 'earth/animal/human/men/young/'
value = 'martin'
path.split('/').reverse.reduce(value){ |r, e| {e.to_sym => r} }

答案 1 :(得分:1)

功能递归方法:

def insert(hash, path, value)
  head, *tail = path
  if tail.empty?
    hash.merge(head => value)
  else
    h = insert(hash[head] || {}, tail, value)
    hash.merge(head => hash.has_key?(head) ? hash[head].merge(h) : h)
  end
end

h1 = insert({}, "animal/human/women/old".split("/"), "Eve")
# {"animal"=>{"human"=>{"women"=>{"old"=>"Eve"}}}}

h2 = insert(h1, "animal/human/men/old".split("/"), "Adam")
# {"animal"=>{"human"=>{"women"=>{"old"=>"Eve"}, 
#                       "men"=>{"old"=>"Adam"}}}}

h3 = insert(h2, "animal/chimpanzee/smart".split("/"), "Caesar")
# {"animal"=>{"human"=>{"women"=>{"old"=>"Eve"}, 
#                       "men"=>{"old"=>"Adam"}}, 
#             "chimpanzee"=>{"smart"=>"Caesar"}}}