将一串哈希拆分为一个哈希数组

时间:2013-12-06 14:55:10

标签: ruby regex hash

我无法使用正则表达式来分割字符串以获得所需的结果。 http://rubular.com/r/ytFwP3ivAv - 根据rubular,这个表达式应该有用。

str = "{"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}, {"DATE"=>"11/26/2013 11:10", "DESC"=>"Hold-up alarm", "LOCATION"=>"4725 S KIRKMAN RD", "DISTRICT"=>"E5", "INCIDENT"=>"2013-00496235"}"

sub_str_array = str.split(/({"[\w"=>\/ :,()-]*})/)

# the desired result - each hash is an element in an array
puts the_split[0] #=> {"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}

还有另一种方法(更简单的方法)将这些字符串哈希转换为哈希数组吗?

3 个答案:

答案 0 :(得分:2)

您可以使用:

require 'json'

yourstr = '[' + '{"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}, {"DATE"=>"11/26/2013 11:10", "DESC"=>"Hold-up alarm", "LOCATION"=>"4725 S KIRKMAN RD", "DISTRICT"=>"E5", "INCIDENT"=>"2013-00496235"}, {"DATE"=>"11/26/2013 11:08", "DESC"=>"Missing person - adult", "LOCATION"=>"4818 S SEMORAN BV 503", "DISTRICT"=>"K1", "INCIDENT"=>"2013-00496198"}, {"DATE"=>"11/26/2013 11:07", "DESC"=>"911 hang up", "LOCATION"=>"311 W PRINCETON ST", "DISTRICT"=>"C2", "INCIDENT"=>"2013-00496231"}' + ']'

my_hash = JSON.parse(yourstr.gsub("=>", ":"))

puts my_hash[0]

答案 1 :(得分:0)

您已将str设置为对象。用引号括起来它应该有用。

最好使用%Q(string goes here)而不是双引号。

答案 2 :(得分:0)

您可以使用eval "[#{str}]",如果 str 是硬编码的,没有人可以更改它。