From: Chris Moline Date: 2001-07-24T04:11:57+09:00 Subject: [ruby-talk:18371] Re: Newbie question: Data structures in Ruby. On Tue, Jul 24, 2001 at 01:26:34AM +0900, Erik wrote: > Pierre-Charles David wrote: > > > > In the end, the page should contain a list of articles, and each article > > > a list of elements. > > > I want to have acces to it like: > > > > > > puts currentpage.articles[2].elements[5].content > > > > > > I want to be able to manipulate this data structure like f.i.: > > > > > > currentpage.articles[2].elements[5].content = 'Hello world' > > > > > > I am not sure if or how I can realise this, could somebody please give > > > me a hint? > > > > Ruby makes attributes hidden ('private') by default. You need to > > explicitely define reader methods for those you want to make accessible: > > Okay, so now I have > > class Page > attr_writer :articles > def initialize > @articles = [] > end > ... > end > > class Article > attr_writer :elements > def initialize > @elements = [] > end > ... > end > > class Element > attr_writer :content > ... > end > > But how do I go from here? > The following does not work: > > currentpage = Page.new > currentpage.articles.push(Article.new) > > I get a 'undefined method: articles' error. > > Regards, > > Erik. You need to use attr_accesor instead of attr_writer because attr_writer only creates the articles= method while attr_accessor creates both articles= and articles. To get the subscripting thing going you need to redefine []. ie class Article def initialize @arr = [1, 2, 3] end def [](i) @arr[i] end end article = Article.new p article print article[1], "\n" print article[0], "\n" print article[2], "\n" Hope this helps, Chris Moline