Created
May 19, 2014 16:08
-
-
Save ifyouseewendy/60775f75c661a87d5272 to your computer and use it in GitHub Desktop.
throw and catch example
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
# catch executes its block. | |
# If a throw is executed, Ruby searches up its stack for a catch block with a tag corresponding to the throw's tag. | |
# If found, that block is terminated, and catch returns the value given to throw. | |
# If throw is not called, the block terminates normally, and the value of catch is the value of the last expression evaluated. | |
# catch expressions may be nested, and the throw call need not be in lexical scope. | |
def routine(n) | |
puts n | |
throw :done, "I'm the return value" if n <= 0 | |
routine(n-1) | |
end | |
catch(:done) { routine(3) } | |
# 3 | |
# 2 | |
# 1 | |
# 0 | |
# => "I'm the return value" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment