ruby - How to return from inside eval?

Viewed 2065

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.)

5 Answers
Related