Zack Shapiro
Zack Shapiro

Reputation: 6998

Why is Ruby concatenating instead of adding 2 values?

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

Upvotes: 0

Views: 818

Answers (3)

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

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

Upvotes: 7

Andrew Grimm
Andrew Grimm

Reputation: 81450

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?

Upvotes: 0

Rym
Rym

Reputation: 650

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

Upvotes: 0

Related Questions