QP School

Full Version: Additions in Ruby
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The easiest way to do additions in Ruby is done by passing the values as follows:


Quote: Wrote:puts 3 + 2


The output on the screen will be 5.

Another way is storing the values in variables and then adding one variable to the other as follows:


Quote: Wrote:num1 = 3
num2 = 2
res1 = num1 + num2
puts res1


The output on the screen will be 5, too.

In case we don't already know the values that should be added
we can ask the user to give us the numbers,
store the user inputs in variables
and then add one variable to another as follows:


Quote: Wrote:puts "Please enter a number here: "
num1 = gets.chomp.to_i
puts "Please enter another number here: "
num2 = gets.chomp.to_i
res1 = num1 + num2
puts res1


Now the output will depend on the user input.
Assumed the user typed 3 first and 2 later the result will be 5 as well.