Given/Input two integer numbers and we have to find the addition of the integer numbers in Ruby.
In this problem, we will find out the way to add two integers in Ruby. Adding two numbers is not as easy as it seems because when we use gets method which stands for getting string, we get the value in the string. We will not get the appropriate result if we add those values.
Methods used:
- puts: This method is used to display some message to the user.
- gets: This method is used to take input from the user.
- .to_i: When we take input through gets method, it is a string. For further calculations, it is mandatory to convert it into an integer for exact results and this method returns the integer conversion of the given string.
- +: It is a mathematical operator which accepts two numerical parameters and returns a numerical value. A binary operator to add two values.
Variables used:
- num1: To store the first value
- num2: To store the second value
- sum: To store the sum i.e. result
Ruby code to add two integer numbers
Output
Code explanation:
This program is to add two integer values and print the sum of these entered numbers. It takes two integers as input and stored them to variables, num1 and num2. Then using the + (arithmetic operator) to store the sum of these variables into the sum and stores this sum and then the puts method prints the sum value with the print statement The sum is $sum.
need an explanation for this answer? contact us directly to get an explanation for this answer