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 valuesint1 = 2int2 = 3**4int3 = 4*5-2int4 = 100# convert to rationals# and print resultsputs int1.to_rputs int2.to_rputs int3.to_rputs int4.to_r
Explanation
- Lines 2 to 5: We create some integer instances.
- Lines 9 to 12: We use the to
_rmethod to convert instances to rationals and the values are printed to the console.