From: dblack@... Date: 2006-11-02T12:31:34+09:00 Subject: Re: Input file, change data, write to file ---2049402039-19209365-1162438286=:19812 Content-Type: MULTIPART/MIXED; BOUNDARY="-2049402039-19209365-1162438286=:19812" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. ---2049402039-19209365-1162438286=:19812 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Thu, 2 Nov 2006, Paul Br wrote: > I'm a ruby newbie trying to read data from a file, make a few changes, > and write the output to a file so it can be imported into a MySQL > database. > > I found a partial solution on page 138 in Maik Schmidt's =E2=80=9CEnterpr= ise > Integration with Ruby=E2=80=9D book but it lacks a means to write the out= put to > a file. > > How can I write the output to a file using the below code? > > For what it's worth, I'll be working with files that contain between > 20,000 =E2=80=93 60,000 rows. > > Below is a data sample: > > 01234567890123456789012345678901234567890123456789012 > > 00123 random text 3.0010/20/200610/21/2006 -3.45 > 00253 more text 275.0007/01/200606/12/2006 12.45 > > Here's what I want the file to look like with tabs between each section: > > 01234567890123456789012345678901234567890123456789012 > 123 random text 3.00 2006-10-20 2006-10-21 -3.45 > 253 more text 275.00 2006-07-01 2006-06-12 12.45 You might find scanf helpful. Here's a little example. Note that the lines of data come from the DATA array, which is automatically read from after __END__. Also, I'm using values_at to manipulate the order in which the values get inserted into the printf string, so that I can put the years first. require 'scanf' DATA.each do |line| values =3D line.scanf("%5d %11c %4f %d/%d/%4d%d/%d/%d %f") printf("%3d%12s %6.2f %04d-%02d-%02d %04d-%02d-%02d %3.2f\n", *values.values_at(0,1,2,5,3,4,8,6,7,9)) end __END__ 00123 random text 3.0010/20/200610/21/2006 -3.45 00253 more text 275.0007/01/200606/12/2006 12.45 Output: 123 random text 3.00 2006-10-20 2006-10-21 -3.45 253 more text 275.00 2006-07-01 2006-06-12 12.45 David --=20 David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org ---2049402039-19209365-1162438286=:19812-- ---2049402039-19209365-1162438286=:19812--