28

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.yml")

My YAML file looks like this:

feeds: [{:url => 'http://www.google.com', :label => 'default'}]

But this doesn't seem to work. How would I go about achieving such a thing?

Thanks, Yuval


EDIT: Sorry, guys. I'm still unclear about how to do this and I suspect it is in part due to my somewhat vague phrasing. I asked a better-phrased, more broad question here. Thank you!

Community
  • 1
  • 1
Yuval Karmi
  • 26,277
  • 39
  • 124
  • 175

3 Answers3

32

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

Ceilingfish
  • 5,397
  • 4
  • 44
  • 71
16

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.

Alex Pan
  • 4,341
  • 8
  • 34
  • 45
jpoppe
  • 2,228
  • 24
  • 25
  • But would this really produce what he requested? I think he wants "feeds" to be a list of hashes, not just a hash. I'm kind of in the same spot, and also don't like the fragile approach that requires trailing space. Any ideas? – estan Mar 18 '15 at 19:09
  • Nevermind. I figured it out. Will post my own answer to this question. – estan Mar 18 '15 at 19:12
7

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.

estan
  • 1,444
  • 2
  • 18
  • 29