And*_*rth 40
puts 1.to_s.rjust(3, "0")
#=> 001
puts 10.to_s.rjust(3, "0")
#=> 010
puts 100.to_s.rjust(3, "0")
#=> 100
Run Code Online (Sandbox Code Playgroud)
上面的代码会将你的user.id转换为字符串,然后String.rjust()方法会考虑它的长度和前缀适当的零数.
saw*_*awa 21
你最好使用字符串格式.
"%03d" % 1 #=> "001"
"%03d" % 10 #=> "010"
"%03d" % 100 #=> "100"
"%03d" % user.id # => what you want
Run Code Online (Sandbox Code Playgroud)
user.id\n#\xe2\x87\x92 5\nuser.id.to_s.rjust(3, \'0\')\n#\xe2\x87\x92 "005"\n
Run Code Online (Sandbox Code Playgroud)\n