Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #---
- #YAML is a format for representing objects as strings.
- #YAML is nice because itβs human-readable
- #---
- #YAML::dump: convert your Person object array into YAML data
- >> require 'yaml'
- => true
- >> class Person
- >> attr_accessor :name, :age
- >> end
- => nil
- >> fred = Person.new
- => #<Person:0x7fed8bc0>
- >> fred.name = "Fred Bloggs"
- => "Fred Bloggs"
- >> fred.age = 45
- => 45
- >> laura = Person.new
- => #<Person:0x7fec7604>
- >> laura.name = "Laura Smith"
- => "Laura Smith"
- >> laura.age = 23
- => 23
- >> test_data = [ fred, laura ]
- => [#<Person:0x7fed8bc0 @name="Fred Bloggs", @age=45>, #<Person:0x7fec7604 @name="Laura Smith", @age=23>]
- >> puts YAML::dump(test_data)
- ---
- - !ruby/object:Person
- age: 45
- name: Fred Bloggs
- - !ruby/object:Person
- age: 23
- name: Laura Smith
- => nil
- #YAML::load: turn YAML code into working Ruby objects.
- >> require 'yaml'
- => false
- >> class Person
- >> attr_accessor :name, :age
- >> end
- => nil
- >> yaml_string = <<END_OF_DATA
- ---
- - !ruby/object:Person
- age: 45
- name: Fred Bloggs
- - !ruby/object:Person
- age: 23
- name: Laura Smith
- END_OF_DATA
- => "---\n- !ruby/object:Person\n age: 45\n name: Fred Bloggs\n- !ruby/object:Person\n age: 23\n name: Laura Smith\n"
- >> test_data = YAML::load(yaml_string)
- => [#<Person:0x7fe71d94 @name="Fred Bloggs", @age=45>, #<Person:0x7fe71ac4 @name="Laura Smith", @age=23>]
- >> puts test_data[0].name
- Fred Bloggs
Add Comment
Please, Sign In to add comment