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 "" ?
YAML is an easy, expressive, data-oriented language that distinguishes itself from document markup languages. YAML Ain't a Markup Language (YAML), and as configuration formats go, it's easy on the eyes.
YAML (/ˈjæməl/ and YAH-ml) (see § History and name) is a human-readable data-serialization language. It is commonly used for configuration files and in applications where data is being stored or transmitted.
Use your YAML REST URL to visualize. Click on the URL button, Enter URL and Submit. Users can also view YAML data file by uploading the file. Online YAML Viewer works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With