Guest User

Untitled

a guest
May 25th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. #---
  2. #YAML is a format for representing objects as strings.
  3. #YAML is nice because it’s human-readable
  4. #---
  5.  
  6. #YAML::dump: convert your Person object array into YAML data
  7.  
  8. >> require 'yaml'
  9. => true
  10. >> class Person
  11. >> attr_accessor :name, :age
  12. >> end
  13. => nil
  14. >> fred = Person.new
  15. => #<Person:0x7fed8bc0>
  16. >> fred.name = "Fred Bloggs"
  17. => "Fred Bloggs"
  18. >> fred.age = 45
  19. => 45
  20. >> laura = Person.new
  21. => #<Person:0x7fec7604>
  22. >> laura.name = "Laura Smith"
  23. => "Laura Smith"
  24. >> laura.age = 23
  25. => 23
  26. >> test_data = [ fred, laura ]
  27. => [#<Person:0x7fed8bc0 @name="Fred Bloggs", @age=45>, #<Person:0x7fec7604 @name="Laura Smith", @age=23>]
  28. >> puts YAML::dump(test_data)
  29. ---
  30. - !ruby/object:Person
  31. age: 45
  32. name: Fred Bloggs
  33. - !ruby/object:Person
  34. age: 23
  35. name: Laura Smith
  36. => nil
  37.  
  38. #YAML::load: turn YAML code into working Ruby objects.
  39.  
  40. >> require 'yaml'
  41. => false
  42. >> class Person
  43. >> attr_accessor :name, :age
  44. >> end
  45. => nil
  46. >> yaml_string = <<END_OF_DATA
  47. ---
  48. - !ruby/object:Person
  49. age: 45
  50. name: Fred Bloggs
  51. - !ruby/object:Person
  52. age: 23
  53. name: Laura Smith
  54. END_OF_DATA
  55. => "---\n- !ruby/object:Person\n age: 45\n name: Fred Bloggs\n- !ruby/object:Person\n age: 23\n name: Laura Smith\n"
  56. >> test_data = YAML::load(yaml_string)
  57. => [#<Person:0x7fe71d94 @name="Fred Bloggs", @age=45>, #<Person:0x7fe71ac4 @name="Laura Smith", @age=23>]
  58. >> puts test_data[0].name
  59. Fred Bloggs
Add Comment
Please, Sign In to add comment