# Text to Hash

**URL:** <https://www.ruby-forum.com/t/text-to-hash/239993>\
**Category:** Rails\
**Created:** [March 23, 2014, 9:38pm UTC](https://www.ruby-forum.com/t/text-to-hash/239993 "2014-03-23T21:38:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![musicdenotation](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ea666f/32.png) [@musicdenotation](https://www.ruby-forum.com/u/musicdenotation)\
**Post date:** [March 23, 2014, 9:38pm UTC](https://www.ruby-forum.com/t/text-to-hash/239993/1 "2014-03-23T21:38:59Z")

</div>

I’m trying to parse some text to break into a Hash with Key Value pairs.

The text looks like this:

“Business Services”,"$2,480.31"  
“Shopping”,"$1,914.75"  
“Home”,"$1,807.53"

Each string is the key, each dollar amount is the associated value.

How would I break this apart?

(I’ve tried using split to break the text up on \r\n and , but I can’t  
seem  
to get the key value association part).

Thanks

---

<div class="post-metadata">

**Author:** ![Shaun\_Gish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/5f9b8f/32.png) [@Shaun\_Gish](https://www.ruby-forum.com/u/Shaun_Gish)\
**Post date:** [March 23, 2014, 11:50pm UTC](https://www.ruby-forum.com/t/text-to-hash/239993/2 "2014-03-23T23:50:23Z")

</div>

Assuming your data is in a file named ‘list.txt’, here’s a crude but  
effective way to do it.

- 
# initialize your result to an empty hash result\_hash = Hash.new

read in your data one line at a time File.open(‘list.txt’).each do  
|line| # break the line on commas, less the last (\n) character into  
fields split\_line =  
line[0…line.length-2].split(’,’) # use the first field, less the  
quotes, as the key key = split\_line[0].gsub(/"/,’’) # use the  
remaining fields, joined with commas, less the quotes as the value  
value  
= split\_line[1…split\_line.length-1].join(’,’).gsub(/"/,’’) # merge  
into your result\_hash result\_hash.merge!({key =\> value}) end\*

---

<div class="post-metadata">

**Author:** ![Shaun\_Gish](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/5f9b8f/32.png) [@Shaun\_Gish](https://www.ruby-forum.com/u/Shaun_Gish)\
**Post date:** [March 24, 2014, 12:04am UTC](https://www.ruby-forum.com/t/text-to-hash/239993/3 "2014-03-24T00:04:59Z")

</div>

Thanks for the reply. I actually ended up learning about the CSV class  
and  
used CSV.parse.

(and the data wasn’t in a file but it looks like the CSV class would  
have  
me covered there too).

Thanks!
