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"

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
to get the key value association part).


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
= 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
used CSV.parse.

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


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs