在ruby中动态创建变量

在ruby中动态创建变量,ruby,Ruby,我希望这样的事情能奏效: while i < 3 do puts i @b[i] = Benchmark.new i += 1 @a += 1 end puts "Here is a #{@a}" puts @b0.inspect puts @b1.inspect puts @b2.inspect 而我

我希望这样的事情能奏效:

while i < 3 do
    puts i
    @b[i] = Benchmark.new
    i += 1
    @a += 1
end

puts "Here is a #{@a}"
puts @b0.inspect
puts @b1.inspect
puts @b2.inspect
而我<3
把我
@b[i]=基准测试。新
i+=1
@a+=1
终止
把“这是一个{@a}”
放置@b0.inspect
放置@b1.inspect
放置@b2.inspect

遗憾的是,它根本不起作用。[]=被视为无法识别的方法

回答了我自己的问题!评估方法就是答案:

puts "Welcome to Benchmark 1.0! How many benchmarks do you wish to perform? (We recommend three)"
number = gets.chomp.to_i
@a = 0
i = 0
while i < number do
    puts i
    eval("@b#{i} = Benchmark.new")
    i += 1
    @a += 1
end

puts "Here is a #{@a}"
puts @b0.inspect
puts @b1.inspect
puts @b2.inspect
puts“欢迎使用Benchmark 1.0!您希望执行多少个基准测试?(我们推荐三个)
number=get.chomp.to_i
@a=0
i=0
而我呢
把我
eval(@b#{i}=Benchmark.new)
i+=1
@a+=1
终止
把“这是一个{@a}”
放置@b0.inspect
放置@b1.inspect
放置@b2.inspect

您也可以使用
实例变量集

3.times{|i| instance_variable_set "@x#{i}", i }
@x1 # => 1
@x2 # => 2
虽然对于这个特定的任务,您应该使用数组,但是使用大量变量而不是列表是新手的错误

benchmarks = []    
n.times { benchmarks << Benchmark.new } # or benchmarks = (0..n).map { Benchmark.new }
benchmarks.each do |bm|
  # do stuff
end
benchmarks=[]

n、 times{benchmarks这显然是一个数组的任务,而不是许多实例变量的任务

benchmarks = number.times.map { Benchmark.new }
puts "Here is a #{number}"
benchmarks.each { |b| puts b.inspect }

但是为什么呢?这对于已经有数据结构的东西来说是不必要的复杂。所以我问了!:)根本没有理由否决投票。努力解决我自己的问题。事实上确实解决了。Stackoverflow用户告诉了a更好的解决方法。