views:

57

answers:

2

how can I create a flat file in ruby?

Flat file is there each letter is placed at a specific column number in the file.

So for example if I am reading some values from the DB:

Name         Class
-------------------
one          A
two          English
three        Math
four         Science

and I want to make a flat file out of it where names are to be between columns 1 to 10 and class is to be between columns 20 to 30. How can I make that file? I know how to write to a file but don't know how to write to a file...with specified columns...?

I tried sprintf from Mladen Jablanović answer

C:\>ruby parse.rb
2342342423
SOMETHING
2342
01/03/2010SDSDFS
234234
sprintf on array        2342342423SOMETHING 2342      01/03/2010SDSDFS234234
+3  A: 

You can use sprintf (or its equivalent String#%) with padded fields:

"%-10s%-10s%-10s" % ['two', '', 'English']
#=> "two                 English   "
Mladen Jablanović
I was typing almost the exact words!
Bryan Ash
does this not work with arrays?
learn_plsql
dope i think my array does not have `''`
learn_plsql
Not sure what you mean.
Mladen Jablanović
+1  A: 

If you don't want to use printf strings you can also use the ljust and rjust methods. If you have non-string data you may need to throw in a to_s call, though at that point printf may be better.

puts "#{name.ljust(10)} #{subject.ljust(10)}"
# => "Three      English"

If you find yourself needing more serious formatting and are familiar with formats from perl or fortran (I think) you might want to look into the FormatR gem, which lets you format like so and can deal with headers, footers, pages sizes and such. Here's a simple snippit:

@)      @<<<<<<<<<<<<<<<<       @#.##
num,    location,             toe_size

And results in

1)      Market                   3.50
Paul Rubel