irb(main):001:0> a = “1+2/3”
=> “1+2/3”
irb(main):002:0> b = eval(a)
=> 1
irb(main):004:0> b.class
=> Fixnum
I would think that eval(a) should return a Float, not a Fixnum.
It’s nothing to do with eval, but rather that if you start with fixnums,
you do fixnum arithmetic. Try replacing 2 with 2.0. That invokes float
division, and every result depending on that input will be float. In
general, you can use x.to_f if you want to force a value to be treated
as float.
This works and I appreciate the response. But it doesn’t solve the
problem that the formulas in the text files already exist & they
weren’t written with Ruby’s arithmetic in mind. My life would be
easier if I didn’t have to go update all of those text files.
Any thoughts on how I can take the string as it stands, “1+2/3” and
get the right answer? I could use regex to replace every integer with
a floating point number, I guess. But that seems kludgey.
Any thoughts on how I can take the string as it stands, “1+2/3” and get
the right answer? I could use regex to replace every integer with a
floating point number, I guess. But that seems kludgey.
David’s suggestion to require ‘mathn’ is a good way to go, but be aware
that 2/3 will evaluate to a rational–precise, but in general slower to
compute with.