Skip to content

Instantly share code, notes, and snippets.

@srpouyet
Created October 14, 2015 11:05
Show Gist options
  • Save srpouyet/91149a6495c1ba4b0d80 to your computer and use it in GitHub Desktop.
Save srpouyet/91149a6495c1ba4b0d80 to your computer and use it in GitHub Desktop.
Fooling around with Ruby's throw - catch
def detector(jedi)
case jedi
when :anakin, :darth_vader
puts "I find your lack of faith disturbing."
throw :dark_side, jedi
when :dooku, :dark_tyranus
puts "There is a fine line between neutral and amoral. In fact, there may be no line there at all."
throw :dark_side, jedi
when :luke
puts "I'm Luke"
throw(:light_side, jedi)
else
puts "Unable to detect allegiance!"
end
end
def catched_detector(name)
catch(:dark_side) do
puts "This line is always evaluated..."
catch(:light_side) do
puts "This line is also always evaluated..."
detector(name)
puts "This line is only evaluated when nothing is thrown..."
end
puts "This line is only evaluated for the light side and when nothing is thrown..."
end
end
# [121] pry(main)> catched_detector(:anakin)
# This line is always evaluated...
# This line is also always evaluated...
# I find your lack of faith disturbing.
# => :anakin
# [122] pry(main)> catched_detector(:luke)
# This line is always evaluated...
# This line is also always evaluated...
# I'm Luke
# This line is only evaluated for the light side and when nothing is thrown...
# => nil
# [123] pry(main)> catched_detector(:yoda)
# This line is always evaluated...
# This line is also always evaluated...
# Unable to detect allegiance!
# This line is only evaluated when nothing is thrown...
# This line is only evaluated for the light side and when nothing is thrown...
# => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment