On 07.03.2007 16:33, Samantha wrote:
> Hello all,
> 
> I have a file that is not a normal csv or tab delimited file.  It is 
> delimited with the pipe | character.
> 
> I Googled and found someone had posted how to parse it... That's all 
> fine and well, but now I need to figure out how I'm going to either (a) 
> import it into a MySQL database or (b) put it in some sort of container 
> that will let me access each field (like an array or a hash).
> 
> If I go through the hash, I'll probably need to assign each field in the 
> file a key, and then populate it.  I'm having a hard time figuring this 
> out.
> 
> If I go the route of MySQL  I know that I'll probably end up using 
> ActiveRecord.
> 
> 
> This is what I have so far that I found from someone's blog (I got the 
> concept from someone's blog and then modified it a bit to see what it 
> was doing and what it would do in relation to my file. What this does, 
> obviously, is puts out the info, a new line between each field, and an 
> extra linefeed between each row... (each group - boy, am I articulate 
> today or WHAT?!)
> 
> File.open("i put the filename here").each do |record|
>  record.split("|").each do |field|
>    field.chomp!
>    puts field
>  end
> end
> 
> 
> So, what I want it to do, is say I have the following fields in the | 
> delimited file:
> 
> category | subcategory | description
> 
> How do I make that stuff into a hash?  I should probably start out small 
> by putting it into a hash first, and then figure out how to deal with it 
> in MySQL.
> 
> If someone could point me in the right direction, of possible libraries 
> that would help or the such, I'd love to go read there and study on it 
> and try to figure it out.  Not asking for answers, just asking for 
> resources. :)

You pretty much got it already.  Just add this:

FIELDS = [:category, :subcategory, :description]
db = []

File.foreach("in") do |line|
   line.chomp!
   rec = {}
   FIELDS.zip(line.split("|")) do |name, val|
     rec[name]=val if val
   end
   db << rec
end

# work with db

(untested)

Kind regards

	robert