Ruby嵌套了每个do循环

时间:2011-11-16 09:08:36

标签: ruby for-loop

我试图通过让这个程序工作来理解嵌套循环。我想使用"每个人都做"如果可能的话,循环的方式。现在循环执行所有的第一个循环,然后是第二个...等...我想做,执行第一个循环1次,然后一次性下降到第二个循环......等等。这是我的代码(粘贴在下面)

所需的输出将是这样的:

index                       3.0                  3.0
+-------------------------------------------------------+
0                          -23.4                -23.4
1                       -2226.74             -2226.74
2                   -1.93464e+07         -1.93464e+07

代码

class LogisticsFunction
  puts "Enter two numbers, both between 0 and 1 (example: .25 .55)."
  puts "After entering the two numbers tell us how many times you"
  puts "want the program to iterate the values (example: 1)."

  puts "Please enter the first number: "
  num1 = gets.chomp

  puts "Enter your second number: "
  num2 = gets.chomp

  puts "Enter the number of times you want the program to iterate: "
  iter = gets.chomp

  print "index".rjust(1)
  print num1.rjust(20)
  puts num2.rjust(30)
  puts "+-------------------------------------------------------+"

  (1..iter.to_i).each do |i|
    print i
  end
    (1..iter.to_i).each do |i|
      num1 = (3.9) * num1.to_f * (1-num1.to_f)
        print num1
    end
      (1..iter.to_i).each do |i|
        num2 = (3.9) * num2.to_f * (1-num2.to_f)
          print num2
      end
end

3 个答案:

答案 0 :(得分:4)

我认为你不必运行三个循环,下面将给出欲望输出

(1..iter.to_i).each do |i|
  print i
  num1 = (3.9) * num1.to_f * (1-num1.to_f)
  print num1.to_s.rjust(20)
  num2 = (3.9) * num2.to_f * (1-num2.to_f)
  print num2.to_s.rjust(30)
end

答案 1 :(得分:4)

您的循环实际上并未嵌套。它们实际上是一个接一个。这就是他们一个接一个地跑的原因。要嵌套它们 - 你必须把它们放在一起。例如:

未嵌套

(1..iter.to_i).each do |i|
  # stuff for loop 1 is done here
end # this closes the first loop - the entire first loop will run now

(1..iter.to_i).each do |j|
  # stuff for loop 2 is done here
end # this closes the second loop - the entire second loop will run now

<强>嵌套:

(1..iter.to_i).each do |i|
  # stuff for loop 1 is done here
  (1..iter.to_i).each do |j|
    # stuff for loop 2 is done here
  end # this closes the second loop - the second loop will run again now
  # it will run each time the first loop is run
end # this closes the first loop - it will run i times

答案 2 :(得分:1)

这样的事情不会解决你的问题吗?

(1..iter.to_i).each do |i|
  num1 = (3.9) * num1.to_f * (1-num1.to_f)
  print num1
  num2 = (3.9) * num2.to_f * (1-num2.to_f)
  print num2
end

从我所看到的你甚至不使用i变量。所以理论上你可以做到

iter.to_i.times do
   # stuff
end