From: Robert Klemme Date: 2007-02-04T02:00:05+09:00 Subject: Re: Saving class with array property with YAML On 03.02.2007 17:13, Martin M�ller wrote: > Hello > > I'm new to Ruby and unfortuantly I can't find an example anywhere to the > following problem. > > I have the following class: > > > class Article > attr_accessor :author > attr_accessor :title > > def inititialize(author, title) > @autor = author > @title = title > end > end > > > class Book > attr_accessor :year > attr_accessor :volume > attr_accessor :articles # array of articles > > def initialize(year, volume) > @year = year > @volume = volume > @articles = Array.new > end > > def insert(author, title) > @articles.push(Article.new(author,title)) > end > end > > > class Bookshelf > ... > end > > > #create book > testbook = Book.new(2007, 1) > > #insert 2 articles into the book > testbook.insert("Martin Mueller", "Confessing that I'm a Ruby Dummy") > testbook.insert("Hillary Clinton", "Elect me and Ruby will save our > planet") > > > #write Book to YAML > File.open("testbook.yaml", "w") {|f| YAML.dump(testbook, f)} > > ----------------------- > > My question is: how can I bring Ruby to save also the Array?? > > I played around with to_yaml_properties but without success. > > thanks a lot for any hint! First you should correct spelling errors of your initialize methods. After you did that, you don't have to do anything: irb(main):049:0> testbook = Book.new(2007, 1) => # irb(main):050:0> testbook.insert("Martin Mueller", "Confessing that I'm a Ruby Dummy") => [#] irb(main):051:0> testbook.insert("Hillary Clinton", "Elect me and Ruby will save our planet") => [#, #] irb(main):052:0> puts testbook.to_yaml --- !ruby/object:Book articles: - !ruby/object:Article autor: Martin Mueller title: Confessing that I'm a Ruby Dummy - !ruby/object:Article autor: Hillary Clinton title: Elect me and Ruby will save our planet volume: 1 year: 2007 => nil irb(main):053:0> Btw, your Book#insert does two things: create an Article and append that to your Book. It's a convenient method. You don't really need that method since you make #articles available anyway so you could as well do: testbook.articles << Article.new( "Martin", "I am a Ruby" ) Kind regards robert