QP School

Full Version: Subtractions 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 subtractions in Ruby is done by passing the values as follows:


Quote:puts 3 - 2


The output on the screen will be 1.

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


Quote:num1 = 3
num2 = 2
res1 = num1 - num2
puts res1


The output on the screen will be 1, too.

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


Quote: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 1 as well.