Trusted answers to developer questions

What is the float.divmod() method in Ruby?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Overview

In Ruby, divmod() is a float method used on a number value to get an array. This array contains the quotient and remainder of the number value.

The quotient is the division of operand one by operand two, which is then rounded using the floor() method. For example, floor(4/2).

The remainder is the modulus of operand one and operand two. For example, mod(4,2).

Syntax

operand_one.divmod(operand_two)

Parameters

This method takes operand_two as a parameter. It’s a number value. It’s mandatory.

Return value

This method returns an array. This array contains the quotient and remainder of operand_one and operand_two.

Example

# create some float values
f1 = 34.344
f2 = 2.423
f3 = -5/2.3
# invoke the coerce method
puts "#{f1.divmod(1)}"
puts "#{f2.divmod(2)}"
puts "#{f3.divmod(3)}"

Explanation

  • Lines 2-4: We create float values f1, f2, and f3.
  • Lines 7-9: We invoke the divmod() method on the float values. Next, we print the results.

RELATED TAGS

float
ruby
Did you find this helpful?