开发者

Is there any built-in method in RoR to fill zero for integer?

开发者 https://www.devze.com 2022-12-18 12:51 出处:网络
If I want \"00001\" instead of \"1\",开发者_JS百科 apart from writing my own filling zero method, is there any built in method can help me fill in zero for the integer? puts \"%05d\" % 1# 00001

If I want "00001" instead of "1",开发者_JS百科 apart from writing my own filling zero method, is there any built in method can help me fill in zero for the integer?


puts "%05d" % 1    # 00001

See: String::%, Kernel::sprintf

Here's what's going on. The "%05d" to the left of the % is a C style format specifier. The variable on the right side of the % is the thing to be formatted. The format specifier can be decoded like this:

  • % - beginning of format specifier
  • 0 - Pad with leading zeros
  • 5 - Make it 5 characters long
  • d - The thing being formatted is an integer

If you were formatting multiple things, you'd put them in an array:

"%d - %s" % [1, "One"]    # => 1 - one


puts 1.to_s.rjust(5,'0')


an_int = 1
'%05d' % an_int #=> 00001
0

精彩评论

暂无评论...
验证码 换一张
取 消