Was pondering the question: what code runs when method level rescue
, else
and ensure
are used in ruby?
TL;DR summary
1 2 3 4 5 6 7 8 9 |
|
- Without
return
the last computed value that is not in theensure
block is returned (this will either be the main body, the rescue block or the else block). - Using
return
in the main body of the method means thatelse
block doesn’t run. - Using
return
in anensure
block always overrides any other value returned by the method, regardless of whether any other section of the method also used thereturn
keyword. - Values from an
ensure
block are only ever returned when thereturn
keyword is used.
Simple function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
ran fn1
ran else1
ran ensure1
Function with error:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
ran fn2
ran rescue2
ran ensure2
Function with return in main body
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
ran fn3
ran ensure3
Function with return in main body and return in ensure block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
ran fn4
ran ensure4
Function with return in main body and in ensure and error raised
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Output:
ran fn5
ran rescue5
ran ensure5