Method – Add Two numbers

This tutorial uses the same code as Add two numbers but includes a function/method to add two numbers together and return a value. The addtwo function has two parameters that are returned back added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

# define a function called addtwo with two parameters
def addtwo(a, b) 
       a + b; # return a + b
end
 
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 as addtwonumbers_function.rb, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Leave a Reply

Your email address will not be published.