假设我们有以下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
答案 0 :(得分:1)
你可以使用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
答案 1 :(得分:1)
我在扩展程序库中使用它:
class OpenStruct
def self.new_recursive(hash)
pairs = hash.map do |key, value|
new_value = value.is_a?(Hash) ? new_recursive(value) : value
[key, new_value]
end
new(Hash[pairs])
end
end
行动中:
struct = OpenStruct.new_recursive(:a => 1, :b => {:c => 3})
struct.a #=> 1
struct.b.c #=> 3