Skip to content

Instantly share code, notes, and snippets.

@ryenski
Created August 2, 2011 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryenski/1120376 to your computer and use it in GitHub Desktop.
Save ryenski/1120376 to your computer and use it in GitHub Desktop.
catch/throw
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