QP School
Quotients and remainders in Ruby - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: Ruby 3 Tutorials, exercises and examples (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=17)
+--- Thread: Quotients and remainders in Ruby (/showthread.php?tid=2499)



Quotients and remainders in Ruby - Qomplainerz - 02-27-2021

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.