Add two numbers

This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

The gets function is able to get a string from the console input, with the string inputted this allows the string function .to_i (to_integer) conversion for the answer to add up to integer values.

The code

print "Please enter number 1 : ";
# get the input from the console, 
val1 = gets;
print "Please enter number 2 : ";
val2 = gets;
# convert the string console inputs to_i (to_integers) and add together
print "Answer : " , (val1.to_i + val2.to_i), "\n";

save that as addtwonumbers.rb.

To run ruby addtwonumbers.rb, and the output would be similar to

Please enter value 1 : 30
Please enter value 2: 23
Answer = 53

Tags: , , ,

5 Responses to “Add two numbers”

  1. Ross Doughty says:

    Thankyou with that I had a problem when trying to add the values of 2 variables together, both which were input by the user. I did try:


    puts M*H


    but that dint work for some reason :/.

    Anyway thanks :).

  2. De-railed says:

    Mine worked great and thnx. Now if I could get my ‘pause’ on it before it snaps off I could get this out of my ‘system’.

  3. reppard says:

    why not just use gets.to_i?

  4. genux says:

    Could do.. just splitting up the code I suppose.

  5. speedy says:


    puts M*H.to_s

Leave a Reply