红宝石 |数值 coerce()函数
coerce()是 Ruby 中的一个内置方法,它返回一个包含两个数字的数组,其中包含两个浮点数。
Syntax: num1.coerce(num2)
Parameters: The function needs a number and ndigits to which the precision of decimal digits is kept. In case no ndigits is passed it takes 0 to be the default value.
Return Value: It returns the smallest number which is greater than or equal to the given number by keeping a precision of n digits of the decimal part.
示例 1 :
Ruby
# Ruby program for coerce() method in Numeric
# Initialize a number
num1 = 1.7
num2 = 1.2
# Function used
arr = num1.coerce(num2)
# Prints coerce() of num
puts arr
Ruby
# Ruby program for ceil() method in Numeric
# Initialize a number
num1 = 2.8
num2 = 0.7
# Function used
arr = num1.coerce(num2)
# Prints coerce() of num
puts arr
输出:
1.7
1.2
示例 2 :
红宝石
# Ruby program for ceil() method in Numeric
# Initialize a number
num1 = 2.8
num2 = 0.7
# Function used
arr = num1.coerce(num2)
# Prints coerce() of num
puts arr
输出:
0.7
2.8