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

use*_*335 2 ruby string hash ruby-on-rails path

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

我想要的是使用"路径"并将其转换为子键,

例如:我有那个参数:path ="earth/animal/human/men/young /"value ="martin"我希望:

  `Global_hash = { earth => { human => { men => { young => "martin"
                                                }
                                       }
                            }
                 }`
Run Code Online (Sandbox Code Playgroud)

path ="earth/animal/human/men/old /"value ="John",我想:

 Global_hash = { earth => { human => { men => { young => "martin",
                                                old   =>  "John" 
                                         }
                                }
                     }
          }
Run Code Online (Sandbox Code Playgroud)

加上另一个

path ="earth/animal/human/women/old /"value ="Eve",我想:

`Global_hash = { earth => { human => { men   => { young => "martin",
                                                  old      =>  "John"
                                                },
                                       women => { old => "Eve"
                                                }
                                     }
                          }
               }
Run Code Online (Sandbox Code Playgroud)

`

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

例子产生:`

earth:
  animal:
    human:
      men:    
        young: "martin"
        old: "John"
      women:
        old: "Eve"
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的提前

Wei*_*Wei 5

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