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

Lindsay Barrett
Lindsay Barrett
234 Points

Ruby While Loop

Hi everyone.

In this block of of code, I don't understand how the print_hello function knows how many times to print "Hello" using "i".

I understand that the "number_of_time" variable takes in the "answer" variable, but i don't understand how a "<" sign knows how many times to print "Hello", as well as how incrementing makes a difference.

Here is the code:

def print_hello(number_of_times)
  i = 0
  while i < number_of_times
    puts "hello"
    i +=1
    end
end

answer = 0
while answer < 5
  print "How many time do you want to print Hello? Enter number greater than 4 to exit."
answer = gets.chomp.to_i
print_hello(answer)
end

1 Answer

Oscar Yuen
PLUS
Oscar Yuen
Courses Plus Student 4,759 Points

That is because i is 0 at the beginning and each time it prints out hello is incremented by one and stop when it reaches number_of_times. So the loop is being run for number_of_times