如何在 Ruby 中解析 YAML 文件? [英] How do I parse a YAML file in Ruby?

查看:64
本文介绍了如何在 Ruby 中解析 YAML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何解析包含以下内容的 YAML 文件:

I would like to know how to parse a YAML file with the following contents:

--- 
javascripts: 
- fo_global:
  - lazyload-min
  - holla-min

目前我正在尝试以这种方式解析它:

Currently I am trying to parse it this way:

@custom_asset_packages_yml = (File.exists?("#{RAILS_ROOT}/config/asset_packages.yml") ? YAML.load_file("#{RAILS_ROOT}/config/asset_packages.yml") : nil)
    if !@custom_asset_packages_yml.nil?
      @custom_asset_packages_yml['javascripts'].each{ |js|
        js['fo_global'].each{ |script|
         script
        }
      }
    end

但它似乎不起作用,并给我一个错误,该值为零.

But it doesn't seem to work and gives me an error that the value is nil.

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

如果我尝试这个,它会输出整个字符串 (fo_globallazyload-minholla-min):

If I try this, it puts out the entire string (fo_globallazyload-minholla-min):

if !@custom_asset_packages_yml.nil?
          @custom_asset_packages_yml['javascripts'].each{ |js|
            js['fo_global']
          }
        end

推荐答案

也许我遗漏了一些东西,但为什么要尝试解析文件?为什么不直接加载 YAML 并检查生成的对象?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

如果您的示例 YAML 在 some.yml 中,则:

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

给我

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

这篇关于如何在 Ruby 中解析 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆