QP School

Full Version: Quotients and remainders in Ruby
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
After reading the official Ruby 3.0.0 documentation I have discovered another cool thing.
Let's assume we want to get the result of 11 / 3 and declare some variables as follows:


Quote:Num1 = 11
Num2 = 3
Quotient = Num1 / Num2
puts "Quotient: " + Quotient.to_s


This will print 3 on the screen.

Now let's get the remainder of the division as follows:


Quote:Option 1: 
Num1 = 11

Num2 = 3
Remainder = Num1 % Num2
puts "Remainder: " + Remainder.to_s

Option 2:
Num1 = 11
Num2 = 3
Remainder = Num1.remainder(Num2)
puts "Remainder: " + Remainder.to_s


Both will print 2 on the screen.

And then let's put the quotient and the remainder together as follows:


Quote:Num1 = 11
Num2 = 3
Quotient = Num1 / Num2
Remainder = Num1 % Num2
Quotient_Remainder = "#{Quotient}, #{Remainder}"
puts "Quotient and remainder: " + Quotient_Remainder.to_s


This will print 3, 2 on the screen.

And now the cool thing.
When using the divmod function Ruby will calculate the quotient and the remainder at the same time.


Quote:Num1 = 11
Num2 = 3
Quotient_Remainder = Num1.divmod(Num2)
puts "Quotient and remainder: " + Quotient_Remainder.to_s


This will print [3, 2] on the screen.