Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby - How to return from inside eval?

Tags:

ruby

eval

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

like image 795
Sony Santos Avatar asked Jul 28 '11 19:07

Sony Santos


2 Answers

Thank you all, but 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.

I didn't like the conditional-like solutions in this case because it would force me (or the user) to add an end at the end.

About using throw/catch or break, I consider the return keyword more intuitive.

like image 194
Sony Santos Avatar answered Nov 22 '22 15:11

Sony Santos


eval'd code is just being run in this place. It's not a function or block. How would you do it without eval? Probably like this:

puts 1
puts 2 
if(conditionFor3And4) 
  puts 3 
  puts 4
end
like image 25
Mchl Avatar answered Nov 22 '22 13:11

Mchl