How To Load Yaml File In Ruby

YAML, short for “YAML Ain’t Markup Language,” is a human-readable and versatile data serialization language. It is often used for configuration files and data exchange between languages with different data structures. In this blog post, we will explore how to load a YAML file in Ruby.

Installing the YAML Library

Before we can start working with YAML files in Ruby, we need to make sure that the YAML library is installed. The good news is that Ruby comes with a built-in library called Psych, which provides support for parsing and emitting YAML files. To use Psych in your Ruby script, all you need to do is require it at the beginning of your file like this:

require ‘yaml’

Loading a YAML File

Loading a YAML file in Ruby is quite simple. You just need to use the YAML.load_file method, passing the path to the YAML file as an argument. This method will read the file, parse its content, and return a Ruby object that represents the data in the file. For example, if you have the following YAML file named config.yml:

  database:
    adapter: postgresql
    encoding: unicode
    pool: 5
  

To load this file and access the data in Ruby, you would do the following:

  require 'yaml'

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

  puts config['database']['adapter'] # Output: postgresql
  puts config['database']['encoding'] # Output: unicode
  puts config['database']['pool']     # Output: 5
  

Working with Arrays and Nested Data

YAML files can also represent arrays and nested data structures. Here’s an example of a more complex YAML file named users.yml:

  - name: Alice
    age: 30
    hobbies:
      - reading
      - hiking
  - name: Bob
    age: 25
    hobbies:
      - video games
      - photography
  

To load this file and access the data in Ruby, you would do the following:

  require 'yaml'

  users = YAML.load_file('users.yml')

  users.each do |user|
    puts "Name: #{user['name']}, Age: #{user['age']}"
    puts "Hobbies:"
    user['hobbies'].each { |hobby| puts "- #{hobby}" }
    puts ""
  end
  

The output would be:

  Name: Alice, Age: 30
  Hobbies:
  - reading
  - hiking

  Name: Bob, Age: 25
  Hobbies:
  - video games
  - photography
  

Conclusion

In this blog post, we’ve learned how to load a YAML file in Ruby using the built-in Psych library. Loading a YAML file is as simple as calling the YAML.load_file method and passing in the file path. The method returns a Ruby object that represents the data contained in the YAML file, making it easy to work with the data in your Ruby script.