I want to format the output of a string in ruby. I can do it using % but I cannot figure 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With