How to export data into a prn file (fixed width with space fill) in Rails

1.3k views Asked by At

I did not see this kind of task done anywhere and was wondering how I could export data in a .prn file format in RoR.

The idea would be to have:

  • field 1 -> length: 6 chars -> content: "blah"
  • field 2 -> length: 8 chars -> content: "foo"
  • field 3 -> length: 4 chars -> content: "bar"

and convert it to a line which would be like:

"blah  foo     bar " -> total 18 chars

I need this because the ERP I'm using only accept fixed width data field.

3

There are 3 answers

0
X2theZ On BEST ANSWER

While both your answers are good, I also found the ruby function ljust():

I then have:

"blah".ljust(6)+"foo".ljust(8)+"bar".ljust(4)

Hope it helps anyone needing the same thing...

Thanks for the help guys

1
maxm On

Look at Array#pack:

a = %w(blah foo bar)
a.pack("A6A8A4")
=> "blah  foo     bar "
0
Sinan Ünür On

I am no Ruby expert, but at the very least, there is sprintf:

C:\Temp> ruby -le "printf '[%-6s%-8s%-4s]', 'blah', 'foo', 'bar'"
[blah  foo     bar ]
 |•••••|•••••••|•••