Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Loops Creating Loops

Nicholas Lee
Nicholas Lee
12,474 Points

Why is hello world not repeated?

i = 0
string ="hello world"
while i <= 10
    string ="Hello world #{i}"
    puts "i is now #{i}"
    i += 1
end
puts "the final value of #{i}"
puts "The final value of #{string}"


What was the significance of having string ="Hello World #{i}" in the code?
Why does it not repeat?
Why does it not read Hello world 11?

Simple, but Jason just blew over it.

4 Answers

hey man,

  • I think the significance of Hello World #{i} is going to come apparent in the next video - it's to do with when the different loops stop/start running
  • It doesn't repeat because you're only change the value of 'string' not puts (put string-ing) it to the page.
  • Because you've stopped the loop of a condition of <= 10. Therefore i will never equal 11. if you put i +=1 at the beginning of the loop, before you redeclare string you would get Hello World 11.

On the last repetition of the loop you've given us, the value of i will be 11.

Nicholas Lee
Nicholas Lee
12,474 Points

I also cannot seem to post the block code. excuse me while I figure that out.

Hey hey--

  1. To post your code, you can refer to this How-to Guide.

  2. It doesn't repeat in the same way that i did because you're only using one puts for Hello World.

If you did it this way instead, you'd get it to repeat.

i = 0

string = "Hello World"

while i <= 10
    string = "Hello World #{i}"
    puts "i is now #{i}"
    puts "Hello World #{i}"
    i += 1
end

puts "The final value of i is #{i}"
puts "The final value of string is #{string}"

Hope that helps!

You are not += or incrementing "Hello World" you are only incrementing i with a += 1. So, you are really only incrementing i from 0 till it reaches or equals 10.