newbi
newbi

Reputation: 305

how can I read a YAML file?

I have such a YAML file:

Company1:
  name: Something1
  established: 2000
#
Company2:
  name: Something2
  established: 1932

reading the YAML file: (** UPDATE **)

    config = YAML.load_file('file.yaml')
    config.each do |key, value|
     if(key == 'name')
      company_name = value
      #year = config['Company1']['established']
      year = config.fetch(key)['established']
     end
   end

** UPDATE ** Now the above code is working, but it shows the result as:

 company1 =>  {"name" => "something1"} => {"established year" => 2000"}

how can I remove the the {} and "" ?

Upvotes: 23

Views: 34748

Answers (2)

Steve Robinson
Steve Robinson

Reputation: 3939

Okay, so this is your YAML file right?

Company1:
  name: Something1
  established: 2000

Company2:
  name: Something2
  established: 1932

Okay now this YAML file actually represents a Hash. The has has two keys i.e Company1, Company2 (because they are the leading entries and the sub entries (name and established) are indented under them). The value of these two keys is again a Hash. This Hash also has 2 keys namely name and established. And they have values like Something1 and 2000 respectively etc.

So when you do,

config=YAML.load_file('file.yml')

And print config (which is a Hash representing the YAML file contents) using,

puts config

you get following output:

{"Company1"=>{"name"=>"Something1", "established"=>2000}, "Company2"=>{"name"=>"Something2", "established"=>1932}}

So we have a Hash object as described by the YAML file.

Using this Hash is pretty straight forward.

Since each company's name and year come in a separate hash held by the outer hash (company1, company2), we can iterate through the companies. The following Code prints the Hash.

config.each do |company,details|
  puts company
  puts "-------"
  puts "Name: " + details["name"]
  puts "Established: " + details["established"].to_s
  puts "\n\n"
end

So in Each iteration we get access to each (key,value) of the Hash. This in first iteration we have company(key) as Company1 and details(value) as {"name"=>"Something1", "established"=>2000}

Hope this helped.

Upvotes: 42

Mori
Mori

Reputation: 27779

YAML uses indentation for scoping, so try, e.g.:

Company1:
  name: Something1
  established: 2000

Company2:
  name: Something2
  established: 1932

Upvotes: 4

Related Questions