What is integer.to_r in Ruby?

Overview

We use the to_r Integer instance method to convert an integer to a rational.

Syntax

integer.to_r

Parameters

This method does not take any parameters.

Return value

This method returns the integer as a rational.

Example

Let’s look at the code below:

# create some integer values
int1 = 2
int2 = 3**4
int3 = 4*5-2
int4 = 100
# convert to rationals
# and print results
puts int1.to_r
puts int2.to_r
puts int3.to_r
puts int4.to_r

Explanation

  • Lines 2 to 5: We create some integer instances.
  • Lines 9 to 12: We use the to _r method to convert instances to rationals and the values are printed to the console.

Free Resources