while while循环中的循环

时间:2014-05-31 05:18:05

标签: ruby loops while-loop

"hello"仅由puts打印三次。应该打印六次,不是吗?

i = 0
j = 0
while(i != 2)
    while(j != 3)
            puts "hello"
            j += 1
    end
i += 1
end

2 个答案:

答案 0 :(得分:1)

您必须在内部j循环之外将0设置为while

i = 0
j = 0
while(i != 2)
    while(j != 3)
            puts "hello"
            j += 1
    end
# this is needed, as inside the upper loop, you made j to 3 after 3 iteration.
# thus you need to reset it to 0 again, to start again 3 times iteration.
j = 0 
i += 1
end
# >> hello
# >> hello
# >> hello
# >> hello
# >> hello
# >> hello

更好的是 -

i = 0
while(i != 2)
  j = 0
  while(j != 3)
    puts "hello"
    j += 1
  end
  i += 1
end

答案 1 :(得分:0)

如果你使用循环{},你可能会更容易 - 即使你必须自己跟踪计数器,我发现它比使用while或xxtimes更容易理解,也可以正常工作。