I have a code which I need to use within eval. Sometimes I need to get out from the eval code, but my tries lead to errors.
E.g.:
# expected to see 1, 2 and 5; not 3 nor 4; and no errors
eval "puts 1; puts 2; return; puts 3; puts 4" # => Error: unexpected return
puts 5
I tried with return, end, exit, break, and I couldn’t get success. exit doesn’t raise errors, but then I don’t get the 5.
(Note: I know that eval is evil, but in this case I need to use it.)
Thank you all, but I found a solution which fits best into my problem:
This way the intuitive
returnkeyword can be used insideevalto get out from it successfully.I didn’t like the conditional-like solutions in this case because it would force me (or the user) to add an
endat the end.About using
throw/catchorbreak, I consider thereturnkeyword more intuitive.