Ruby Integer to_r function with example

The to_r function in Ruby converts the value of the number to a rational.

Syntax: number.to_r

Parameter: The function takes the number which is to be converted to a rational number.

Return Value: The function returns the rational number.

Example #1:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for to_r function 
   
# Initializing the number
num1 = 51
num2 = 10.78
num3 = 1690.89
num4 = 183
    
# Prints the number as rational
puts num1.to_r
puts num2.to_r
puts num3.to_r
puts num4.to_r

chevron_right


Output:

51/1
6068600497881743/562949953421312
7436612865160643/4398046511104
183/1

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for to_r function 
   
# Initializing the number
num1 = 312
num2 = 98.09
num3 = 190.23
num4 = 2.5
    
# Prints the number as rational
puts num1.to_r
puts num2.to_r
puts num3.to_r
puts num4.to_r

chevron_right


Output:

 312/1
3451235058193531/35184372088832
6693123102458511/35184372088832
5/2
My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.