Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string to a condition in Ruby

I actually have a string called "cond". This is the content of that string:

"20 < 50"

I would like to insert it into a condition like this: (example)

if 20 < 50
return "Hello"

But that condition is a string, so I can't write this:

if cond
return "Hello"

So I would like to know if it is possible to convert a string to a condition to set in an "if" condition. And if it is possible, how can I do it ?

Thank you.

like image 409
TW147 Avatar asked Jun 30 '11 14:06

TW147


1 Answers

eval might just be your friend here:

>> eval('20 < 50')
=> true

However, eval will execute the arbitrary code inside its argument; you should be sure that your cond can't contain anything detrimental to your system's health!

like image 53
Chowlett Avatar answered Oct 17 '22 22:10

Chowlett