Created
January 21, 2009 15:43
-
-
Save ivey/50004 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Here's the example from the book: | |
input = '' | |
while input != 'bye' | |
puts input | |
input = gets.chomp | |
end | |
puts 'Come again soon!' | |
# Let's go through it line by line | |
# First, set input to an empty string. This is so we | |
# can check it the first time through the loop. Without | |
# this, the first time through the loop it would be | |
# undefined and we'd get an error | |
input = '' | |
# This creates the loop, and reads exactly like it does in | |
# English: "while input is not equal to the string 'bye', do | |
# some stuff" | |
while input != 'bye' | |
# This is the part inside the loop, which will get | |
# run over and over, as long as input isn't set to 'bye' | |
puts input | |
input = gets.chomp | |
end | |
# When/if input gets set to 'bye', then after the loop | |
# finishes that time through, it will leave the loop and | |
# end up here | |
puts 'Come again soon!' | |
# So, to write your own loop, you need 3 things: | |
# * initial state/variables | |
# * a condition to check | |
# * some code to run inside the loop | |
some_state = false | |
while !some_state | |
do_something | |
do_something_else | |
# be sure to change some_state when you're done, | |
# or else you'll loop forever and ever and ever and | |
# ever and ever and ever and ever....which is fine, | |
# if that's what you want. | |
if we_are_done | |
some_state = true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment