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.


On Feb 13, 2006, at 2:15 PM, Joel VanderWerf wrote:

> Ian Whitney wrote:
>> I'm trying to calculate the results of formulas that are stored in  
>> text
>> files.
>>
>> For example, a file may contain the line: 1+2/3
>>
>> I want to take that line & get the result of the formula, 1.66  
>> (roughly)
>>
>> The way to do this seems to be Kernel.eval. But I can't get it to  
>> work
>> correctly. Here's my irb session:
>>
>> 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.
>
> -- 
>       vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407
>