Friday, July 29, 2011

How to return from inside eval

I have a code which I need to use within eval. Sometimes I need to get out from the middle of eval code, but how?

In PHP I can use the return keyword, but it doesn't work on Ruby:

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

After many tries and a question in StackOverflow, I found a solution which fits best into my problem:

lambda do
  eval "puts 1; puts 2; return; puts 3; puts 4"
end.call
puts 5

This way the intuitive return keyword can be used inside eval to get out from it successfully.

You can find alternative ways at StackOverflow.

No comments:

Post a Comment