What is integer.to_i method in Ruby?

Overview

The to_i method of an integer instance returns the integer instance itself because it is already an integer.

Syntax

integer.to_i

Parameters

This method does not take any parameters.

Return value

The value returned is the integer integer itself.

Example

Let’s look at the code below:

# create some integers
int1 = 23
int2 = -10
int3 = 1
int4 = 30**100
# invoke the to_i method
puts int1.to_i
puts int2.to_i
puts int3.to_i
puts int4.to_i

Explanation

  • Lines 2 to 5: We create integers int1, int2, int3, and int4.
  • Lines 8 to 11: We invoke the to_i method on the integer instances and the returned values are printed to the system console.

Free Resources