【问题标题】:Reference YAML Node using method parameter使用方法参数引用 YAML 节点
【发布时间】:2019-06-09 12:51:41
【问题描述】:

我加载了一个 yaml,需要为它定义一个范围,以引用一个特定的节点。

myYaml = YAML.load_file('myfile.yml').with_indifferent_access

一般情况下,我可以做到

myYaml[:first_node][:first_child][:second_child]

但是,我想将路径传递给一个方法来为我确定它的范围。我正在努力做这样的事情..

scope_path = [:first_node,:first_child,:second_child]

def scope(scope_path)
 myYAML[scope_path]
end

# 所以我需要代码将我的 scope_path 参数转换为

myYaml[:first_node][:first_child][:second_child]

【问题讨论】:

    标签: ruby yaml ruby-on-rails-5.2


    【解决方案1】:

    你可以简单地使用Hash#dig:

    myYaml.dig(:first_node, :first_child, :second_child)
    

    【讨论】:

    • 值得注意的是,splat 运算符 (*) 可能对 OP 的用例有用:def scope(scope_path); MY_YAML.dig(*scope_path); end
    猜你喜欢
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多