Ruby 整数 to_r函数与示例
Ruby 中的to_r函数将数字的值转换为有理数。
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.
示例 #1:
# 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
输出:
51/1
6068600497881743/562949953421312
7436612865160643/4398046511104
183/1
示例 #2:
# 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
输出:
312/1
3451235058193531/35184372088832
6693123102458511/35184372088832
5/2