Text to Hash

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

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*

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!