Poll: Was this article helpful for you?
You do not have permission to vote in this poll.
Yes
100.00%
1 100.00%
No
0%
0 0%
Total 1 vote(s) 100%
* You voted for this item. [Show Results]

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Quotients and remainders in Ruby
#1
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.
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Messages In This Thread
Quotients and remainders in Ruby - by Qomplainerz - 02-27-2021, 08:51 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Everything you need to know about Ruby Qomplainerz 0 857 07-25-2023, 09:53 AM
Last Post: Qomplainerz
  Additions in Ruby Qomplainerz 0 1,717 03-14-2021, 10:13 AM
Last Post: Qomplainerz
  Subtractions in Ruby Qomplainerz 0 1,640 03-08-2021, 11:42 AM
Last Post: Qomplainerz
  Predecessor in Ruby Qomplainerz 0 1,759 02-28-2021, 10:31 AM
Last Post: Qomplainerz
  Successor in Ruby Qomplainerz 0 1,714 02-28-2021, 10:29 AM
Last Post: Qomplainerz
  Least common multiple in Ruby Qomplainerz 0 1,817 02-28-2021, 09:11 AM
Last Post: Qomplainerz
  Floor and precisions in Ruby Qomplainerz 0 1,768 02-28-2021, 08:40 AM
Last Post: Qomplainerz
  Ceil and precisions in Ruby Qomplainerz 0 1,779 02-28-2021, 08:35 AM
Last Post: Qomplainerz
  Getting the currently installed Ruby version Qomplainerz 0 1,772 02-26-2021, 08:23 AM
Last Post: Qomplainerz
  Getting started with Ruby 3 Qomplainerz 0 2,072 02-26-2021, 07:34 AM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 1 Guest(s)