Why my addition code is not working?


print "type first num."
num1 = gets.chomp
print "type second num."
num2 = gets.chomp
print num1 + num2


What is happening? Are num1 and num2 being joined (concatenated) or summed (addition)?

num1 => "3"
num2 => "5"

outcome => "35"

num1 => 3
num2 => 5

outcome => 8


'chomp' returns a string. '+' catenates two strings. If the user enters
A and B on the two prompts, AB will be printed.

To convert a string into a number, use for instance the methods to_i or
to_f (depending on what kind of number you would like to have).

I also recommend to print a newline. The simplest way would be to
replace print by puts.



i want to add num1 and num2, but they are being concatenated (joined) in the outcome.


Then that means your inputs are strings. We need to convert them to integers so they can be added together for a sum.

a = gets.chomp
b = gets.chomp
c = a.to_i + b.to_i

print c


For future reference, even though you may see authors chaining string methods to gets.chomp, avoid it. Let it be their unworthy practice, and not yours. get a string and remove trailing white space. That return would rightly be passed to a validation process to determine type and range, etc. Not something that can be done when chaining a method to gets.chomp.

This just occured to me along the lines of validation...

c = a.to_i || 0 + b.to_i || 0

In float terms, that could be written,

c = a.to_f || 0.0 + b.to_f || 0.0


Just tested and it appears Ruby returns 0 when inputs don't match .to_i.The logic is not needed..

a = gets.chomp
b = gets.chomp
c = a.to_i + b.to_i

puts c

c = (a.to_i || 0).to_i + (b.to_i || 0).to_i

puts c

=> nil


Thank you, it is working now. Sorry for replying late i was in a problem.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.