Math parser?

Is there a build in parser in the Math class to do this?

I don't think so, but we might roll our own.

module Math
  def self.eval(expression)
    allowed_characters = Regexp.escape('+-*/.')
    safe_expression =
expression.match(/[\d#{allowed_characters}]*/).to_s
    Kernel.eval(safe_expression)
  end
end

I believe the above is safe, but don't shoot me if it's not.

Tor Erik

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED ...

Super. Ill try that. I would need to add this to the math class in the
ruby root library?

Tor Erik Linnerud wrote:

You can put this file in the lib directory, and call it something simple like custom_math.rb, then in your application.rb do include Math and it should include that.

If you're willing to wrap it with some error handling you can let
'eval' take care of it:

eval("100*500/2.5")
=> 20000.0

(It understands parens, too).

eval("100*(500/2.5)")

=> 20000.0

AndyV wrote:

If you're willing to wrap it with some error handling you can let
'eval' take care of it

Just be carefull so you don't unintentionally allow arbitrary code to be
executed. (Depending on the use case this may or may not be an issue).

If you change
Regexp.escape('+-*/.')

to

Regexp.escape('+-*/.() ')

then you can use parentheses and spaces in my example too.

Tor Erik