Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
879 views
in Technique[技术] by (71.8m points)

ruby - How to work with leading zeros in integers

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

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

Why is it converting 0112 into 74?

How can convert 0112 to a string "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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...