From: Robert Klemme Date: 2013-02-16T23:53:31+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 11:54 PM, Jesse F. wrote: > I came up with the same answer. Almost the same code, except I don't > need the Form to know which Items are its. but you said earlier: > Form has an each method to iterate over FormItems. Then how do you access them (e.g. in #each) if they are created in Form's constructor and immediately forgotten? > They're read only, and Form > has all the data. But Form has defaults and variables FormItems needs to > read/write. So FormItems are read only but they modify their container? You could then make them immutable. FormItem = Struct.new :container, :data do def display puts "This is a silly example: #{data}" container.shown += 1 self end end class Form attr_accessor :shown def initialize(data) @items = data.map {|d| FormItem[self, d].freeze} @shown = 0 end include Enumerable def each(&b) @items.each(&b) self end end ff = Form.new 5.times.to_a ff.each {|fi| fi.display} puts ff.shown ff.first.data = "boom" > I was looking for something like a .Net interface. I guess I just have > to stop fighting it. It's always a good strategy to not expect your new programming language to be the same as the old one. :-) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/