如何将字符串数组转换为哈希数组?

时间:2013-11-24 18:28:34

标签: ruby string csv methods hash

接下来是两个字符串的数组。我想知道如何将它转换为两个哈希的数组。

["{: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}"]

我采用了不同的路径并以不同的格式保存了csv文件,这使我能够更轻松地操作我的ruby文件中的数据,因此不再需要打开此问题。有人可以删除这个问题吗?当我发布问题时,我会尝试更加具体(初学者知识有限)。对此表示歉意并感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您首先要删除不平衡的右括号,然后在两个字符串上调用eval将它们返回到哈希值:

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} 

答案 1 :(得分:1)

从阵列的开头删除一个括号,从末尾删除两个:

a = ["{: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}"]

a.map {|s| s.sub("{","").sub("}","").gsub(":","").gsub(/\"/,"").split(',')}.map {|e| \
    e.map {|f|k, v = f.strip.split("=>");[k.to_sym, v]}}.map {|e| Hash[*e.flatten]}

 # => [{:date=>"11/24/13 1239 PM", :gross_profit=>"32.5", :cogs=>"9.75",
        :net_profit=>"38.5", :units_sold=>"5"},
       {:date=>"11/24/13 1241 PM", :gross_profit=>"29.5", :cogs=>"8.9",
        :net_profit=>"34.2", :units_sold=>"4"}]

让我们打破这个:

b = a.map {|s| s.sub("{","").sub("}","").gsub(":","").gsub(/\"/,"").split(',')}
  # => [["date=>"11/24/13 1239 PM", " gross_profit=>32.5", " cogs=>9.75", \
         " net_profit=>38.5", " units_sold=>5"], \
        ["date=>"11/24/13 1241 PM", " gross_profit=>29.5", " cogs=>8.9", \
         " net_profit=>34.2", " units_sold=>4"]]

    c = b.map {|e| e.map {|f|k, v = f.strip.split("=>");[k.to_sym, v]}}
      # => [[[:date, "11/24/13 1239 PM"], [:gross_profit, "32.5"], [:cogs, "9.75"], \
             [:net_profit, "38.5"], [:units_sold, "5"]], \
            [[:date, "11/24/13 1241 PM"], [:gross_profit, "29.5"], [:cogs, "8.9"], \
             [:net_profit, "34.2"], [:units_sold, "4"]]]

        c.map {|e| Hash[*e.flatten]} # => result above