How to Use the floor Method in Ruby

Contents
In this article, you will learn how to use the floor method in Ruby.
The floor Method
In Ruby, the floor method is a built-in method of the Numeric class that rounds a number down to the nearest integer.
Syntax
The syntax for using the floor method is as follows:
number.floor
Parameters
number
: The numeric value that you want to round down to the nearest integer.
Example
Here’s an example:
x = 3.5
y = 4.8
z = -2.3
puts x.floor # Output: 3
puts y.floor # Output: 4
puts z.floor # Output: -3
In the above example, we have used the floor method to round down the values of x, y, and z to their nearest integers.
It’s important to note that the floor method always rounds a number down, even if the decimal part is 0.5 or greater. To round a number to the nearest integer, you can use the round method instead.
Here’s some more information about the floor method in Ruby:
- The floor method can be used with any numeric data type in Ruby, including integers, floats, and decimals.
- If the number is already an integer, the floor method will return the same integer.
- The floor method is a non-destructive method, which means it does not modify the original number. Instead, it returns a new rounded value.
- The floor method can also be used with negative numbers. In this case, it will round the number down to the nearest integer that is smaller than the given number.
- If you try to use the floor method with a non-numeric data type, you will get a NoMethodError.
Here’s an example that demonstrates some of these properties:
num1 = 10
num2 = 3.14
num3 = -5.6
num4 = 7/3.0 # returns a float
puts num1.floor # Output: 10
puts num2.floor # Output: 3
puts num3.floor # Output: -6
puts num4.floor # Output: 2
In the above example, we have used the floor method with different numeric values, including an integer, a float, a negative number, and a division that returns a float. As you can see, the floor method rounds down each number to the nearest integer according to the rules mentioned earlier.