Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to know how to do a parse of a txt with the following structure:

Each item in the file is separated by the TAB key.

The columns are:

purchaser name, item description, item price, purchase count, merchant address, merchant name.

purchaser name  item description    item price  purchase count  merchant address    merchant name
Jo?o Silva  R$10 off R$20 of food   10.0    2   987 Fake St Bob's Pizza
Amy Pond    R$30 of awesome for R$10    10.0    5   456 Unreal Rd   Tom's Awesome Shop
Marty McFly R$20 Sneakers for R$5   5.0 1   123 Fake St Sneaker Store Emporium
Snake Plissken  R$20 Sneakers for R$5   5.0 4   123 Fake St Sneaker Store Emporium

After analyzing this data I need to send to a normalized database and with the respective tables created.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use CSV for parsing files with separators, e.g.:

require 'csv'

CSV.foreach('your_file.txt', col_sep: "	", headers: true).map do |row|
  row.to_h
end
#=> [{"purchaser"=>"Jo?o", "name"=>"St", "item"=>"R$20", "description"=>"off" ...}, 
#    {"purchaser"=>"Amy", "name"=>"Rd", "item"=>"awesome", "description"=>"of", ..}, ...]

It seems like this data is ready to process. A more common way is using comma-separated value for files like this, so I would suggest you change file format if you can.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...