Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

"hello" is printed by puts only three times. It is supposed to be printed six times, isn't it?

i = 0
j = 0
while(i != 2)
    while(j != 3)
            puts "hello"
            j += 1
    end
i += 1
end
share|improve this question
    
Note that in Ruby there generally are better ways to do traditional for and while loops. For example: 2.times { 3.times { puts "hello" } } is equivalent to your code. –  Daniël Knippers May 31 at 8:06

2 Answers 2

up vote 1 down vote accepted

You have to set j to 0 outside the inner while loop.

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

Better is -

i = 0
while(i != 2)
  j = 0
  while(j != 3)
    puts "hello"
    j += 1
  end
  i += 1
end
share|improve this answer
    
Wow ! thank you for your fast answer! I feel a bit stupid but I wont forget it :p –  guillaume May 31 at 5:25

It may be easier for you if you work with loop {} - even though you have to keep track of the counter yourself, I find it much easier to understand instantly than using while, or x.times which also works fine.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.