Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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)

like image 345
Radek Avatar asked Jul 06 '11 23:07

Radek


2 Answers

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"). 
like image 189
Zabba Avatar answered Sep 22 '22 06:09

Zabba


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"
like image 26
DGM Avatar answered Sep 20 '22 06:09

DGM