From: "Jesús Gabriel y Galán" Date: 2009-01-12T18:07:29+09:00 Subject: Re: Dynamically created attributes On Mon, Jan 12, 2009 at 10:03 AM, Jesús Gabriel y Galán wrote: > On Mon, Jan 12, 2009 at 9:25 AM, Peter Marks wrote: >> I'd like to specify a quantity of object attributes when creating an >> instance of an object. For example, I would like to create a Grid object >> with 4 different 'row' attributes like this: Grid.new(4). Here's some >> dirty code that does that: >> >> class Grid >> #Creates row1, row2, etc. depending on row arg >> def initialize(rows) >> row_count = 1 >> rows.times do >> instance_eval "@row#{row_count} = 'xxx'" >> row_count += 1 >> end >> end >> end >> >> It's dirty, but it creates the attributes. I don't see how to >> dynamically create accessor methods for all these attributes though. Any >> suggestions? I sense there's a better way to do this. >> -- >> Posted via http://www.ruby-forum.com/. >> >> > > Maybe this is cleaner: > > class Object > def singleton_class > class << self; self; end > end > end > > class Grid > def initialize rows=0 > rows.times do |i| > instance_variable_set "@row#{i}", "initial value" > singleton_class.instance_eval {attr_accessor "row#{i}"} > end > end > end > > irb(main):020:0> a = Grid.new 3 > => # @row1="initial value"> > irb(main):021:0> a.methods.grep /row/ > => ["row0", "row0=", "row1", "row1=", "row2", "row2="] Ooops, my solution starts with 0, while you wanted to start with 1. Anyway, an easy change. Nevertheless, I agree with Stefano that this would be better off implemented as an array, instead of having individual variables for each "field". Jesus.