开发者

how to format string output using % in ruby?

I want to format the output of a string in ruby. I can do it using % but I cannot fi开发者_如何转开发gure it out.

Instead of 201107070928 I want to output 2011\07\070928

puts "%.4s\\%.2s\\%s" % "201107070928"

gives me an error:`%': too few arguments (ArgumentError)


That's not how you use it for formatting a date. The way to use % formatting is:

puts "%.4s\\%.2s\\%s" % ["1","2","3"]

So, you need multiple parameters - one for each of the format specifiers.

If you need to print & format a date from a string-date, first convert the string to a date/time object and then use strftime:

Presuming the input is date and a time:

Time.parse("201107070928").strftime("%Y\\%m\\%d%H%M"). 


I'm going to put this in an answer rather than a comment just because I'm more impressed with the possibility. Using String#unpack, we can handle a 4 digit / 2 digit / anything with:

"201107070928345345345".unpack("a4a2a*").join('/')
 => "2011/07/070928345345345"
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜