6

I need a method that through an input string to do a calculation, like this

function = "(a/b)*100"
a = 25
b = 50
function.something
>> 50

have some method for it?

3
  • 1
    If you are too confident use Kernel#eval... Like eval(function). Commented Jul 10, 2014 at 19:51
  • 3
    I don't know what you want to do with it but please do not trust user's input, i.e. do not use something coming from end-users in your "string to be evaluated". Commented Jul 10, 2014 at 19:56
  • My honest suggestion is.. Please change your interface, so that you don't need to use any such #eval. Think it some other way. No point to use any eval family in doing such math. Commented Jul 10, 2014 at 20:07

2 Answers 2

8

You can use instance_eval:

function = "(a/b)*100"
a = 25.0
b = 50

instance_eval function
# => 50.0

Be aware though that using eval is inherently insecure, especially if you use external input, as it may contain injected malicious code.

Also note that a is set to 25.0 instead of 25, since if it is an integer a/b would result in 0 (integer).

Sign up to request clarification or add additional context in comments.

3 Comments

Beware, this can run anything in your application, ex: User.destroy_all.
@BrunoMuceliniMergen, yes, I've mentioned that in my answer
@RustamA.Gasanov Something is saving your time.. Doesn't mean it is clean,superb and all.. It can take whole life of the app.. Be sure always.
3

You can take a look at the gem dentaku, which is math and logic formula parser and evaluator.

require 'dentaku'

a = 25.0
b = 50
function = "(#{a}/#{b})*100"

calculator = Dentaku::Calculator.new
calculator.evaluate(function) # => 50.0

Don't use any eval.

3 Comments

"Don't use any eval." There is a time and a place for eval. eval is fine when you know what's being eval'd. If the string is created by the script, and is based on sanitized data then it's safe. It's unsafe when the data is unknown/not-sanitized.
@theTinMan You are right. But still I will practice the good habit of not using eval, and I will look for a math parser, like the one I have shown here. I don't support,eval using, where there is a way. #instance_eval or #instance_exec has other purposes, but not they are for mathematical calculations.. Any way it is matter of taste, about avoiding risk.
formula shall stay "(a/b)*100" and then add the variables {a: 25.0, b: 50} to the evaluate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.