Skip to content

Instantly share code, notes, and snippets.

@sahilshah-rr
Created August 29, 2012 21:19
Show Gist options
  • Save sahilshah-rr/3519117 to your computer and use it in GitHub Desktop.
Save sahilshah-rr/3519117 to your computer and use it in GitHub Desktop.
def...rescue...ensure...end returns value from ensure block only if explicit directive to do so is present
def abc(bool)
a=b=0
a+=10
raise StandardError if bool
"returning from main func a#{a} b#{b}" # returned unless bool
rescue
"returning from rescue a#{a} b#{b}" # returned if bool
ensure
b+=10 # always executed
puts "printing from ensure a#{a} b#{b}" # always executed
"returning from ensure a#{a} b#{b}" # never returned
end
abc false
# printing from ensure a10 b10
#=> "returning from main func a10 b0"
abc true
# printing from ensure a10 b10
#=> "returning from rescue a10 b0"
def abc(bool)
a=b=0
a+=10
raise StandardError if bool;
"returning from main func a#{a} b#{b}" # never returned
rescue
"returning from rescue a#{a} b#{b}" # never returned
ensure
b+=10 # always executed
puts "printing from ensure a#{a} b#{b}" # always executed
# Using an explicit return statement in the ensure block
return "returning from ensure a#{a} b#{b}" # always returned
end
abc false
# printing from ensure a10 b10
#=> "returning from ensure a10 b10"
abc true
# printing from ensure a10 b10
#=> "returning from ensure a10 b10"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment