Ruby 整数 to_s函数与示例
Ruby 中的to_s函数返回一个字符串,其中包含以基数为基数的 int 的位值表示(介于 2 和 36 之间)。如果参数中没有提供基数,则假定基数为 10 并返回。
Syntax: number.to_s(base)
Parameter: The function takes the number and a base to which is to be converted. If no base is provided in the parameter, then the default parameter is assumed to be 10.
Return Value: The function returns a string containing the place-value representation of int with the given radix base.
示例 #1:
Ruby
# Ruby program for to_s function
# Initializing the number
num1 = 10
num2 = 16
num3 = 298
num4 = 183
# Prints the string after
# conversion into base
puts num1.to_s
puts num2.to_s
puts num3.to_s(2)
puts num4.to_s(8)
Ruby
# Ruby program for to_s function
# Initializing the number
num1 = 120
num2 = 189
num3 = 132
num4 = 8
# Prints the string after
# conversion into base
puts num1.to_s(5)
puts num2.to_s(20)
puts num3.to_s(2)
puts num4.to_s
输出:
10
16
100101010
267
示例 #2:
红宝石
# Ruby program for to_s function
# Initializing the number
num1 = 120
num2 = 189
num3 = 132
num4 = 8
# Prints the string after
# conversion into base
puts num1.to_s(5)
puts num2.to_s(20)
puts num3.to_s(2)
puts num4.to_s
输出:
440
99
10000100
8