# While what's true?

Ex 35 … we’re in the game with a grouchy bear and the evil Cthulhu …

The definition of the bear_room function includes the following while loop, spanning lines 30 to 46 …

``````while true
print "> "
choice = \$stdin.gets.chomp

if choice == "take honey"
elsif choice == "taunt bear" && !bear_moved
puts "The bear has moved from the door. You can go through it now."
bear_moved = true
elsif choice =="taunt bear" && bear_moved
elsif choice == "open door" && bear_moved
gold_room
else
puts "I got no idea what that means."
end
end
``````

So the while loop begins …

while true

My question is … while what is true?? In the Common Student Questions for Ex 35, someone has asked why the code says “while true”? The response is that “while true” makes an infinite loop.

I thought we were supposed to avoid infinite loops, so this is even more puzzling. But - are we using an infinite loop here because we always want to go through this while loop when we’re in the bear_room?

I’d appreciate a little more explanation about “while true” …

Anything you put after `while` or `if` eventually boils down to true or false. That’s how boolean logic works. When you write a test like

``while x < 3``

then the programming language checks whether the precdiate `x < 3` is true or false.
But single values also have a truth value, so if `x` is some integer, in

``while x``

the test evaluates to false if x is 0, otherwise it’ll be true. Generally speaking, most things that are not empty or zero are considered true in the context of boolean operations.

Combined with the fact that you can write ‘literal’ tests that don’t depend on a changing variable this allows you to write ‘infinite loops’. You usually do

``while true``

but you could also write

``while 1``

or

``while "this is a tru-ish string"``

to do the same thing: These ‘tests’ always evaluate to true so the loop never exits unless you tell it to explicitly in the body.

You generally don’t want a loop to never end, but infinite loops can be a useful construct if you make sure that there are explicit exit points. In your code there are two of them: the `dead` function and the `gold_room` function. The loop runs until it hits a condition that leads to either of those.

Does that help?

1 Like

Got it!

That’s great - thanks, florian!

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.