Ruby - How to return from inside eval?

I have a code that I need to use in eval . Sometimes I need to exit eval code, but my attempts lead to errors.

eg:.

 # 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 could not succeed. exit does not cause errors, but then I do not get 5.

(Note: I know that eval is evil, but in this case I need to use it.)

+6
source share
4 answers

Thanks to everyone, but I found a solution that works best for my problem:

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

Thus, the intuitive return keyword can be used inside eval to successfully exit it.

I did not like conditionally-like solutions in this case, because it would force me (or the user) to add end to the end.

On using throw/catch or break , I find the return keyword more intuitive.

+4
source

The eval'd code runs only in this place. This is not a function or block. How would you do this without eval? Probably like this:

 puts 1 puts 2 if(conditionFor3And4) puts 3 puts 4 end 
+3
source

You can not. You can return from methods and exit blocks or loops, but not eval.

Instead, you can try throw / catch block

 eval " should_stop = true catch :stop do puts 1 puts 2 throw :stop if should_stop puts 3 end " 

or that:

  should_stop = true catch :stop do eval " puts 1 puts 2 throw :stop if should_stop puts 3 " end 

or just make a conditional expression as Mchl said, since you probably want it to be a conditional stop, not just always, but a catch throw will let you jump out of the block no matter how many levels you need, which makes it more reliable if you need to break out of a nested loop or something like that.

+3
source

You could just use conditional expressions instead of early returns.

+2
source

Source: https://habr.com/ru/post/893810/


All Articles