如何使用整数中的前导零

问题描述:

在Ruby中处理前导零的正确方法是什么?

What is the proper way to deal with leading zeros in Ruby?

0112.to_s
 => "74"
0112.to_i
 => 74

为什么将 0112 转换为 74

如何将 0112 转换为字符串0112

我想定义一个方法整数作为参数,并以数字的降序返回。

I want to define a method that takes integer as a argument and returns it with its digits in descending order.

但是当我有前导零时,这对我来说似乎不起作用:

But this does not seem to work for me when I have leading zeros:

def descending_order(n)
  n.to_s.reverse.to_i
end


0开头的数字文字是一个八进制表示形式,除了以 0x 开头的文字表示十六进制数字或 0b 表示二进制数。

A numeric literal that starts with 0 is an octal representation, except the literals that start with 0x which represent hexadecimal numbers or 0b which represent binary numbers.

1 * 8**2 + 1 * 8**1 + 2 * 8**0 == 74

要将其转换为 0112 ,请使用 字符串#% 内核#sprintf ,带有适当的格式字符串:

To convert it to 0112, use String#% or Kernel#sprintf with an appropriate format string:

'0%o' % 0112  # 0: leading zero, %o: represent as an octal
# => "0112"