'How do you convert an array of strings to an array of hashes? [closed]

An array of two strings follows. I would like to know how to convert it to an array of two hashes.

["{:date=>\"11/24/13 12:39 PM\", :gross_profit=>32.5, :cogs=>9.75, :net_profit=>38.5, :units_sold=>5}",
   "{:date=>\"11/24/13 12:41 PM\", :gross_profit=>29.5, :cogs=>8.9, :net_profit=>34.2, :units_sold=>4}"]

I took a different route and saved the csv file in a different format which allowed me to more easily manipulate the data in my ruby file so this question no longer needs to be open.



Solution 1:[1]

You'll want to start by removing the unbalanced right bracket, then call eval on both strings to return them to hashes:

2.0.0p247 :010 > arr = [["{:date=>\"11/24/13 12:39 PM\", :gross_profit=>32.5, :cogs=>9.75, :net_profit=>38.5, :units_sold=>5}",
2.0.0p247 :011 >          "{:date=>\"11/24/13 12:41 PM\", :gross_profit=>29.5, :cogs=>8.9, :net_profit=>34.2, :units_sold=>4}"]]
 => [["{:date=>\"11/24/13 12:39 PM\", :gross_profit=>32.5, :cogs=>9.75, :net_profit=>38.5, :units_sold=>5}", "{:date=>\"11/24/13 12:41 PM\", :gross_profit=>29.5, :cogs=>8.9, :net_profit=>34.2, :units_sold=>4}"]] 

2.0.0p247 :013 > hash1, hash2 = arr.flatten.map {|str| eval(str)}
 => [{:date=>"11/24/13 12:39 PM", :gross_profit=>32.5, :cogs=>9.75, :net_profit=>38.5, :units_sold=>5}, {:date=>"11/24/13 12:41 PM", :gross_profit=>29.5, :cogs=>8.9, :net_profit=>34.2, :units_sold=>4}] 

2.0.0p247 :014 > hash1
 => {:date=>"11/24/13 12:39 PM", :gross_profit=>32.5, :cogs=>9.75, :net_profit=>38.5, :units_sold=>5} 

2.0.0p247 :015 > hash2
 => {:date=>"11/24/13 12:41 PM", :gross_profit=>29.5, :cogs=>8.9, :net_profit=>34.2, :units_sold=>4} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CDub