Forum: Ruby Simple Ruby Calculator & Function Problems - Help!

Bacf885eeb3ccdfa0027e8342ef01194?d=identicon&s=25 Ed Goulart (edgoulart)
on 2014-05-07 22:48
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)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.