2

有人能建议我这样做吗?(一切都在主题中:D)

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

例如:我有那个参数: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 文件,其中所有对象都按部分排序,这要归功于它们的路径。

感谢提前

4

2 回答 2

5
path = 'earth/animal/human/men/young/'
value = 'martin'
path.split('/').reverse.reduce(value){ |r, e| {e.to_sym => r} }
于 2012-07-13T11:38:20.107 回答
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"}}}
于 2012-07-13T12:51:29.443 回答