Hash inside YAML file?

后端 未结 3 1782
失恋的感觉
失恋的感觉 2020-12-30 21:41

I want to include a hash and list inside a YAML file that I\'m parsing with the following command:

APP_CONFIG = YAML.load_file(\"#{RAILS_ROOT}/config/config.         


        
相关标签:
3条回答
  • 2020-12-30 22:04

    Ceilingfish's answer is maybe technically correct, but he recommends to use a white space at the end of a line. This is prone to errors and is not a good practice!

    This is how I would do it:

    Create a settings.yaml file with the following contents:

    ---
    feeds:
      :url: 'http://www.google.com'
      :label: 'default'
    

    This will create the following hash after the YAML file has been loaded:

    irb(main):001:0> require 'yaml'
    => true
    irb(main):002:0> YAML.load_file('settings.yaml')
    => {"feeds"=>{:url=>"http://www.google.com", :label=>"default"}}
    irb(main):003:0> 
    

    In this example, I also use symbols since this seems to be the preferred way of storing Ruby keys in Ruby.

    0 讨论(0)
  • 2020-12-30 22:19

    Old question, but since I was in a similar spot... Like Jasper pointed out, Ceilingfish's answer is correct. But you can also do

    feeds:
     - url: 'http://www.google.com'
       label: 'default'
    

    to avoid having to rely on trailing whitespace after the dash.

    0 讨论(0)
  • 2020-12-30 22:21

    You can mark it up like this

    feeds:
     - 
      url: 'http://www.google.com'
      label: 'default'
    

    Note the spacing is important here. "-" must be indented by a single space (not a tab), and followed by a single space. And url & label must be indented by two spaces (not tabs either).

    Additionally this might be helpful: http://www.yaml.org/YAML_for_ruby.html

    0 讨论(0)
提交回复
热议问题