how can I read a YAML file?

后端 未结 2 1017
既然无缘
既然无缘 2020-12-30 01:19

I have such a YAML file:

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

reading the YA

相关标签:
2条回答
  • 2020-12-30 01:31

    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.

    0 讨论(0)
  • 2020-12-30 01:44

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

    Company1:
      name: Something1
      established: 2000
    
    Company2:
      name: Something2
      established: 1932
    
    0 讨论(0)
提交回复
热议问题