NOT executing if statement

#!/usr/bin/ruby
def sumtotal(x, y, mathop)
puts "Given Math Operation is: "+mathop
puts “X = #{x}”
puts “Y = #{y}”
puts “\n”
if mathop == “+”
z = x + y
elsif mathop == “-”
z = x - y
elsif mathop == “*”
z = x * y
puts(z)
elsif mathop == “/”
z = x / y
else
z = “Invalid Math Operation”
end
return z
end

puts "Enter Math Operation: "
funop = gets()
#puts "Given Math Operation is: "+funop
tot = sumtotal(10,20, funop)
puts “Sum of 2 Number is #{tot}”

So what’s the problem? Are you trying to say that the function isn’t
doing anything, not even giving you back “Invalid Math Operation”?

I can believe that it is at least giving you that, rather than doing
the proper math. Try checking the exact value of mathop. Put quotes
around it. I think you’ll discover you need one more operation. This
shouldn’t be too big a challenge to sink your teeth into. :wink:

-Dave

Dave A. wrote in post #1044404:

So what’s the problem? Are you trying to say that the function isn’t
doing anything, not even giving you back “Invalid Math Operation”?

I can believe that it is at least giving you that, rather than doing
the proper math. Try checking the exact value of mathop. Put quotes
around it. I think you’ll discover you need one more operation. This
shouldn’t be too big a challenge to sink your teeth into. :wink:

-Dave

mathop=mathop.strip
This help Dave. Thanks for explanation

On Mon, Feb 6, 2012 at 11:04 PM, Hasmukh P. [email protected]
wrote:

mathop=mathop.strip
This help Dave. Thanks for explanation

You could have found it easier by relying on #inspect for debugging:

def calc(x, y, mathop)
printf “x=%p y=%p mathop=%p\n”, x, y, mathop

case mathop
when ‘+’
x + y
when ‘-’
x - y

else
raise “Invalid math operation #{mathop.inspect}”
end
end

“case” also seems more appropriate here. And the name “sumtotal” is
misleading. :slight_smile:

Kind regards

robert

On Mon, Feb 6, 2012 at 17:04, Hasmukh P. [email protected] wrote:

Dave A. wrote in post #1044404:

I think you’ll discover you need one more operation. This
shouldn’t be too big a challenge to sink your teeth into. :wink:

mathop=mathop.strip

That will work too. I was thinking of “chomp” – the bit about
sinking your teeth into it was supposed to be a hint. :wink:

-Dave

tot = sumtotal(10,20, funop.chop)

On Wed, Feb 8, 2012 at 4:53 PM, Dave A.
[email protected] wrote:

sinking your teeth into it was supposed to be a hint. :wink:
LOL

RFC:

irb(main):001:0> class String; def munch;gsub(/\s+/, ‘’) end end
=> nil
irb(main):002:0> “foo bar baz .”.munch
=> “foobarbaz.”

:wink:

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs