Hi!

The script bellow (Ruby 1.9.3p484 on windows 7) is running OK, but I’m

having a (simple?) problem; It’s not prepared to accept parenthesis in a

formula to calc… I’ve been trying a lot of search in the net but I’m

still not able to solve the problem. Would anyone, please, give me a

hand, or a hint?

Thanks,

Ed

def is_number? expr

return false if expr.nil?

expr = “#{expr}” # we need this condition in case the

expr is a number

expr.match /^(\d+|\d+.\d+)$/ # since match() is defined only for

strings

end

def is_number? expr

return false if expr.nil?

expr = “#{expr}” # we need this condition in case the

# expr is a number

expr.match /^(\d+|\d+.\d+)$/ # since match() is defined only for

strings

end

def calc(expr)

return expr.to_f if is_number? expr

expr.gsub!(" “,”") # clean the string from whitespaces pay attention

# to the order: + and - should come before * and / can you figure out

why?

arr = expr.split /+/

return arr.inject(){|x,y| calc(x) + calc(y) } if arr.size > 1

arr = expr.split /-/

return arr.inject(){|x,y| calc(x) - calc(y) } if arr.size > 1

arr = expr.split /*/

return arr.inject(){|x,y| calc(x) * calc(y) } if arr.size > 1

arr = expr.split ///

return arr.inject(){|x,y| calc(x) / calc(y) } if arr.size > 1

end

print "Formula to calc: "

puts calc(gets)