R
Ralph Shnelvar
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? Is there a more Ruby-ish way to do
anything else in the code, above?
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? Is there a more Ruby-ish way to do
anything else in the code, above?