Toby Joiner
Toby Joiner

Reputation: 4376

convert string calculation to value of calculation rails

I have a string that looks like this:

"(12.0+10)*31"

I need to be able to convert that to the value:

(12.0+10)*31 = 682

I have tried some obvious ones like .to_f but that didn't work

I only care about the value (682), I don't really need to see the calculation.

I am sure there is some easy rails thing that does this that I can't find.

Thanks for any help

Upvotes: 1

Views: 206

Answers (1)

ipd
ipd

Reputation: 5714

You can use eval for this, i.e. in IRB:

>> eval "(12.0+10)*31"
=> 682.0

Then if it needs to be an integer you just call to_i on the result.

ian.

Upvotes: 3

Related Questions