Useful Methods from Numeric Class in Ruby


There are several methods in Ruby that can be used on numbers. In this article, we will explore some of these useful methods and how to use them.

number.even in Ruby

This method is used when we want to check if a particular number is even or not. Consider the code shown below −

Example

Consider the code shown below.

num = 14
puts num.even?

num = 19
puts num.even?

Output

It will produce the following output.

true
false

number.odd in Ruby

This method is used when we want to check if a particular number is odd or not. Consider the code shown below −

Example

Consider the code shown below.

num = 14
puts num.odd?

num = 19
puts num.odd?

Output

It will produce the following output.

false
true

number.ceil in Ruby

Floats are rounded up to the nearest integer using the ".ceil" method. This method returns an integer. Consider the code shown below −

Example

Consider the code shown below.

num = 8.3
puts num.ceil

num = 9.1
puts num.ceil

Output

It will produce the following output.

9
10

number.floor in Ruby

Floats are rounded down to the nearest integer using the ".floor" method. This method returns an integer. Consider the code shown below −

Example

Consider the code shown below.

num = 8.3
puts num.floor

num = 9.1
puts num.floor

Output

It will produce the following output.

8
9

number.next in Ruby

The next method is used to return the next consecutive integer. Consider the code shown below.

Example

Consider the code shown below.

num = 8
puts num.next

num = 9
puts num.next

Output

It will produce the following output.

9
10

Updated on: 12-Apr-2022

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements