From: Marnen Laibow-Koser Date: 2009-11-23T23:05:34+09:00 Subject: Re: More on psuedo arrays; Better way? Ralph Shnelvar wrote: > Newbie here: > > Consider: > > > > N_X_METHODS = 20 > > class X > 20.times do |i| > define_method "x%02d=" % i do |arg| > # the puts, below, is just a placeholder for a more complicated > method > puts "Hi " + i.to_s + arg.to_s > end > end > end > > > m = Array.new(N_X_METHODS) do |i| > ("x%02d=" % i).to_sym > end > > p m > > > 10.times do |i| > x = X.new > > # select a random method > x.method(m[rand(i % N_X_METHODS)]).call(i) > end > > > > > > > Let's focus on the line > x.method(m[rand(i % N_X_METHODS)]).call(i) > > > Is there a better way to do this? x.send("x#{rand(i % N_X_METHODS)]".to_sym)) You don't need m at all. > Is there a more Ruby-ish way to do > anything else in the code, above? Yes: use operators to make X look like a real array. class X def []=(i, arg) puts "Hi " + i.to_s + arg.to_s end end N_X_METHODS = 20 10.times do |i| x = X.new # should this be outside the loop? x[rand(i % N_X_METHODS)] = i end Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.