From: "Jesús Gabriel y Galán" Date: 2013-02-16T05:56:53+09:00 Subject: Re: How do you associate the items of a collection instance with the collection in a smart Ruby way? On Fri, Feb 15, 2013 at 7:36 PM, Jesse F. wrote: > This is a conceptual question about Ruby. I think I may be thinking of > this wrong: > > I have a Form class that is a container for FormItems. > > In initialize, Form takes in a bunch of row data that is used to > initialize the FormItems. Form has an each method to iterate over > FormItems. > > FormItems has a bunch of methods and attributes. > > I want to associate information to instances of Form that FormItems can > use. > > How do I associate the object of a container with the container? Or what > is a smart Ruby way (I know there are a lot of ways)? So a FormItem belongs to one Form, and you want it to be able to read things from it? One way would be to pass the Form instance to the FormItems, either in the constructor, if the Form is constructing the items, or in the code that tells a Form that this item belongs to it. First case: class Form def initialize @items = [] @items << FormItem.new(:item, :init, :params, self) [...] # other items end end class FormItem def initialize item, init, params, container @container = container [...] #rest of initialization end end Note in the constructor of the Form, we are passing self to the form items. Form items would be able then to call methods of form using their instance variable @container. Second way: class Form def initialize @items = [] end def add_item item item.container = self @items << item end end class FormItem attr_reader :container def initialize item, init, params [...] #rest of initialization end end f = Form.new item = FormItem.new :a, :b, :c f.add_item item Hope this gives you some ideas, Jesus.