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
returnthe last computed value that is not in theensureblock is returned (this will either be the main body, the rescue block or the else block). - Using
returnin the main body of the method means thatelseblock doesn’t run. - Using
returnin anensureblock always overrides any other value returned by the method, regardless of whether any other section of the method also used thereturnkeyword. - Values from an
ensureblock are only ever returned when thereturnkeyword 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