Ruby - File YaML

Introduction

YAML stands for YAML Ain't Markup Language,

It is a special text-based markup language used to do data serialization that's readable by humans.

The YAML library comes as part of Ruby's standard library.

Demo

require 'yaml' 

class Person # from  w w w .j av a  2  s .co  m
  attr_accessor :name, :age 
end 

fred = Person.new 
fred.name = "Java" 
fred.age = 45 

laura = Person.new 
laura.name = "Json" 
laura.age = 23 

test_data = [ fred, laura ] 

puts YAML::dump(test_data)

Result

YAML::dump converts your Person object array into YAML data.

YAML::load turns YAML code into working Ruby objects.

Demo

require 'yaml' 

class Person # from   w ww.j  ava  2  s .  c o m
  attr_accessor :name, :age 
end 

yaml_string = <<END_OF_DATA 
--- 
- !ruby/object:Person 
  age: 45 
  name: MyName
- !ruby/object:Person 
  age: 23 
  name: New Name
END_OF_DATA 

test_data = YAML::load(yaml_string) 
puts test_data[0].name 
puts test_data[1].name

Result

Here YAML::load converts the YAML data back into the test_data array of Person objects.