public
Created

catch/throw

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.