gFontaniva
gFontaniva

Reputation: 903

Convert string to a function in ruby-on-rails

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?

Upvotes: 6

Views: 2034

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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.

Upvotes: 3

Uri Agassi
Uri Agassi

Reputation: 37409

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

Upvotes: 8

Related Questions