From: "David A. Black" Date: 2009-10-03T03:02:13+09:00 Subject: Re: operating on a selection of objects Hi -- On Fri, 2 Oct 2009, James French wrote: > Hi, > > I want to be able to do operations to a selection of objects, something like this: > > class Config > attr_accessor :name > end > > class ConfigSelection > > def initialize(*configs) > @configs = configs > end > > def name=(n) > @configs.each{|c| c.name = n} > end > > end > > a = Config.new > a.name = "a" > > b = Config.new > b.name = "b" > > s = ConfigSelection.new(a, b) > s.name = "s" > > > I was wondering if there might be a more elegant way of doing this, without having to explicitly duplicate all of Config's attributes in ConfigSelection? Here's a different approach from the method_missing ones, just to give you some further ideas: class Config ATTRIBUTES = [:name, :age, :email] attr_accessor *ATTRIBUTES end class ConfigSelection def initialize(*configs) @configs = configs end Config::ATTRIBUTES.each do |attr| define_method("#{attr}=") do |val| @configs.each {|c| c.send("#{attr}=", val) } end end end David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2)