假设我们有以下 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
最佳答案
您可以使用 OpenStruct以及为此的递归函数,它看起来像这样:
require 'ostruct'
def deep_open_struct(hash)
internal_hashes = {}
hash.each do |key,value|
if value.kind_of?( Hash )
internal_hashes[key] = value
end
end
if internal_hashes.empty?
OpenStruct.new(hash)
else
duplicate = hash.dup
internal_hashes.each do |key,value|
duplicate[key] = deep_open_struct(value)
end
OpenStruct.new(duplicate)
end
end
f = YAML.load_file('my.yml')
struct = deep_open_struct(f)
puts struct.books.book_one
关于ruby-on-rails - 是否有内置函数来访问嵌套的 yaml 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11137518/