YAML (YAML Ain't Markup Language) is a human-readable data serialization format that integrates seamlessly with Ruby. It's widely used for configuration files, data storage, and inter-language data sharing.
Ruby provides built-in support for YAML through its standard library. The yaml
module offers simple methods to parse and generate YAML data.
To parse YAML in Ruby, use the YAML.load
method:
require 'yaml'
yaml_string = "
name: John Doe
age: 30
hobbies:
- reading
- swimming
"
data = YAML.load(yaml_string)
puts data['name'] # Output: John Doe
puts data['hobbies'][1] # Output: swimming
To convert Ruby objects to YAML, use the YAML.dump
method:
require 'yaml'
data = {
'name' => 'Jane Smith',
'age' => 28,
'skills' => ['Ruby', 'Python', 'JavaScript']
}
yaml_output = YAML.dump(data)
puts yaml_output
YAML.safe_load
instead of YAML.load
when parsing untrusted YAML data to prevent potential security vulnerabilities.YAML in Ruby is frequently used for:
To deepen your understanding of YAML in Ruby, explore these related topics:
By mastering YAML in Ruby, you'll enhance your ability to work with structured data and configuration files in your Ruby projects.