Created
August 2, 2011 15:08
-
-
Save ryenski/1120376 to your computer and use it in GitHub Desktop.
catch/throw
This file contains hidden or 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
marble_jar = 0 | |
count = 0 | |
catch :jar_is_full do | |
1000000000000.times do |marble| | |
count += 1 | |
# grab a random-sized marble | |
marble = rand(9) | |
if marble_jar + marble > 1000 | |
# The jar is full | |
throw :jar_is_full | |
else | |
# Insert the marble | |
marble_jar += marble | |
end | |
end | |
end | |
puts "\n== There are #{marble_jar} marbles in the jar, but we only had to iterate #{count} times to find that out.\n\n" | |
# == There are 998 marbles in the jar, but we only had to iterate 258 times to find that out. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment