# Beginner Question: Formatted Text Data -\> Hash -\> Database

**URL:** <https://www.ruby-forum.com/t/beginner-question-formatted-text-data-hash-database/148333>\
**Category:** Rails\
**Created:** [September 11, 2008, 8:15pm UTC](https://www.ruby-forum.com/t/beginner-question-formatted-text-data-hash-database/148333 "2008-09-11T20:15:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jisho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/c4cdca/32.png) [@Jisho](https://www.ruby-forum.com/u/Jisho)\
**Post date:** [September 11, 2008, 8:15pm UTC](https://www.ruby-forum.com/t/beginner-question-formatted-text-data-hash-database/148333/1 "2008-09-11T20:15:03Z")

</div>

I have a text document that has formatted data in it, and I am  
attempted to determine the best way to parse the data to break it up  
into hashes that I can then write to my databases. I suppose my issue  
is determining where to tell Ruby to STOP reading in data to write  
into the database. The file would be similar to this:

User: Username  
Phone: Phone number  
Address: Address  
Comments: Comments  
Data1: Data  
Data2: Data  
Data3: Data  
User: Username  
Phone: Phone number  
Address: Address  
Comments: Comments  
Data1: Data  
Data2: Data  
User: Username  
Phone: Phone number  
Address: Address  
Comments: Comments  
Data1: Data  
Data2: Data

It’s not that difficult to chomp the \n and use a split to create a  
hash in a loop, but how do tell Ruby to start a new database write  
process if it hits a new “user” key value? Should I write a case  
statement to check each line for a “user” key and use that line to  
call a new instance of my database class/method? Is there a faster or  
more efficient way?

---

<div class="post-metadata">

**Author:** ![Jisho](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/c4cdca/32.png) [@Jisho](https://www.ruby-forum.com/u/Jisho)\
**Post date:** [September 11, 2008, 8:59pm UTC](https://www.ruby-forum.com/t/beginner-question-formatted-text-data-hash-database/148333/2 "2008-09-11T20:59:55Z")

</div>

I’ll be interested to see what responses you get, but I can’t think of a  
more efficient way. I’d try something like:

my\_file.each\_line do |line|  
if line ~= /$User/ and this\_user.username.length \> 0 then  
if this\_user.save then  
puts(“Saved user #{this\_user.username}”)  
else  
puts(“Problem saving  
#{this\_user.username}!:\n#{this\_user.errors}”)  
end  
this\_user = User.new  
end  
attribute, val = line.split(/:\s\*/)  
this\_user.send(attribute.lower, val)  
end

That’s air-code obviously–may be wildly off…
