From: ara.t.howard@... Date: 2006-07-07T12:47:41+09:00 Subject: Re: quick metaprogramming question: collecting arguments across calls On Fri, 7 Jul 2006, William Morgan wrote: > Hi all, > > Quick question: is there a better way to write Foo.contains below? > Forcing the lexical scoping like this feels wrong. > > class Foo > def self.contains *o > @contents ||= [] > @contents += o > contents = @contents > define_method(:contents) { contents } > end > end > > class Bar < Foo > contains :goat, :boat > contains :stoat > end > > p Bar.new.contents # => [:goat, :boat, :stoat] if the behaviour is useful - abstract it: harp:~ > cat a.rb module Container module ClassMethods def contents() @contents ||= [] end def contains(*list) contents.push *list.flatten end end def contents() self.class.contents end def self.included other other.extend ClassMethods super end end class Foo include Container end class Bar < Foo contains :goat, :boat contains :stoat end p Bar.new.contents # => [:goat, :boat, :stoat] harp:~ > ruby a.rb [:goat, :boat, :stoat] regards. -a -- suffering increases your inner strength. also, the wishing for suffering makes the suffering disappear. - h.h. the 14th dali lama