【发布时间】:2012-06-21 11:50:29
【问题描述】:
假设我们有以下 YAML 结构:
books:
book_one: "Some name"
book_two: "Some other name"
如果我们像这样加载文件:
f = YAML.load_file("my.yml")
我们可以访问book_one,例如:f["books"]["book_one"]。是否有一个内置函数可以接受如下字符串:books.book_one 并返回相同的值?
编辑:这是我目前所拥有的,它似乎有效:
...
@yfile = YAML.load_file("my.yml")
...
def strings_for(key)
key_components = key.split(".")
container = @yfile
key_components.each_with_index do |kc,idx|
if container && container.kind_of?(Hash) && container.keys.include?(kc)
container = container[kc]
else
container = nil
end
end
container
end
【问题讨论】:
-
顺便说一句,
inject- gist 可以做得更好。这就是我在其中一个项目中使用的。 -
你看过
YAML中的YPath方法吗?我看起来像一个强大的东西,但我怀疑我自己会转向它。
标签: ruby-on-rails ruby yaml