0

I wrote a small program to test out Textmate 2 (I'm fairly new to Ruby) and it's spitting out that 4 + 9 = 49 instead of 13 for some reason.

def add(x,y)
  c = x + y
  return c
end

puts "please enter a value "
a = gets.chomp
puts "please enter another value "
b = gets.chomp

printMe = add(a,b)

puts printMe
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Zack Shapiro
  • 6,648
  • 17
  • 83
  • 151
  • 7
    Because "4" + "9" is "49" :) – pilcrow Dec 13 '11 at 20:05
  • A good question to ask at this point is, do you understand the difference between strings and numberics? That "4" + "9" = "49" should have instantly triggered understanding of what happened. – the Tin Man Jan 28 '12 at 18:05

3 Answers3

7

It's because gets returns a string:

def add(x,y)
  c = x + y
end

puts "please enter a value "
a = gets.to_i
puts "please enter another value "
b = gets.to_i

printMe = add(a,b)

puts printMe
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
0

It's treating the input as string by default I guess, try:

def add(x,y)
  (x.to_i + y.to_i)
end

Also, no need to return in ruby or place in variable c, it will automagically return the last line of code as output

Rym
  • 650
  • 4
  • 16
  • It's not as convenient or sense-making as the gets.to_i approach. When one supplies add("x", "y"), one would then get a result different from "xy", which would be unexpected a weird. And that's not great for program readability. – bcc32 Dec 13 '11 at 22:24
0

If you did puts printMe.inspect, you'd be able to see for yourself that it's "49", not 49, and that a and b are strings. For more debugging hints, see How do I debug Ruby scripts?

Community
  • 1
  • 1
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338