Skip to content

Instantly share code, notes, and snippets.

@ifyouseewendy
Created May 19, 2014 16:08
Show Gist options
  • Save ifyouseewendy/60775f75c661a87d5272 to your computer and use it in GitHub Desktop.
Save ifyouseewendy/60775f75c661a87d5272 to your computer and use it in GitHub Desktop.
throw and catch example
# 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