Problem loading a YAML file

I’m having issues loading a YAML file. Here is the YAML file (named
test.yml):

foo: 5
bar: some string

Here is my Ruby:

C:\noozler\trunk>ruby script/console
Loading development environment (Rails 2.0.2)

require ‘yaml’
=> []

File.exists?(“test.yml”)
=> true

t = YAML::load(“test.yml”)
=> “test.yml”

t[‘bar’]
=> nil

I would expect t[‘bar’] to show: “some string”.

Any ideas?

On Jan 28, 3:19 pm, Keith C. [email protected] wrote:

require ‘yaml’
=> []

File.exists?(“test.yml”)
=> true

t = YAML::load(“test.yml”)
=> “test.yml”

t[‘bar’]
=> nil

I would expect t[‘bar’] to show: “some string”.

You want YAML::load_file which, erm, loads a file; not YAML::load
which parses from the string you pass it.

Keith C. wrote:

I’m having issues loading a YAML file. Here is the YAML file (named
test.yml):

foo: 5
bar: some string

Here is my Ruby:

C:\noozler\trunk>ruby script/console
Loading development environment (Rails 2.0.2)

require ‘yaml’
=> []

File.exists?(“test.yml”)
=> true

t = YAML::load(“test.yml”)
=> “test.yml”

t[‘bar’]
=> nil

I would expect t[‘bar’] to show: “some string”.

Any ideas?

The “t” you are loading is a String… always check the types for a
clue… :slight_smile:

irb(main):002:0> require ‘yaml’
=> true
irb(main):003:0> File.open(“test.yml”) {|f| YAML::load(f)[‘bar’]}
=> “some string”

hth

ilan

On Jan 28, 1:19 pm, Keith C. [email protected] wrote:

require ‘yaml’
=> []

File.exists?(“test.yml”)
=> true

t = YAML::load(“test.yml”)
=> “test.yml”

WARNING! Right here, you see that the result of loading “test.yml” is
“test.yml”. It’s not a Hash like you expected.

Apparently YAML.load takes a raw YAML string, not a filename. Try:

irb(main):004:0> y = YAML.load( IO.read( ‘test.yml’ ) )
=> {“foo”=>5, “bar”=>“some string”}

Ilan B. wrote:

hth

ilan

It definitely helped! Thank you sir.

Try this:

require ‘yaml’

t = YAML::load( File.open(‘test.yaml’) )
t[‘bar’]

Keith C. ha scritto:

Or

t = YAML::load_file ‘test.yaml’

George

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs