开发者

how to create a flat file in ruby

开发者 https://www.devze.com 2023-01-08 19:27 出处:网络
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.

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


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

"%-10s%-10s%-10s" % ['two', '', 'English']
#=> "two                 English   "


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
0

精彩评论

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

关注公众号