# Simple Ruby Calculator & Function Problems - Help!

**URL:** <https://www.ruby-forum.com/t/simple-ruby-calculator-function-problems-help/240952>\
**Category:** Ruby\
**Created:** [May 7, 2014, 10:48pm UTC](https://www.ruby-forum.com/t/simple-ruby-calculator-function-problems-help/240952 "2014-05-07T22:48:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Detlef\_R](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/58f4c7/32.png) [@Detlef\_R](https://www.ruby-forum.com/u/Detlef_R)\
**Post date:** [May 7, 2014, 10:48pm UTC](https://www.ruby-forum.com/t/simple-ruby-calculator-function-problems-help/240952/1 "2014-05-07T22:48:37Z")

</div>

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)
