2015-08-22 61 views
3

我有一个字符串:将字符串转换为元组,哈希或数组

"(\"Doe, John\",12345)" 

我想这个字符串转换成一个元组("Doe, John",12345),散列{"Doe, John" => 12345}或数组["Doe, John",12345]

我不知道如何将它分成两个元素"Doe, John"12345。我想避免使用regex。我不能使用split,因为我得到["(\"Doe", "John", "12345)"]

+0

散列来自哪里?用户输入?管道数据? – Beartech

+0

它是一个'PG :: Result',所以在结果中有很多这种类型的哈希。 – jdesilvio

+1

你应该击中'(“Doe,John”,12345)',因为它不是Ruby对象。 –

回答

2
Hash[*s[1..-2].gsub('"', '').reverse.sub(',', '|').reverse.split('|')] 

结果

{"Doe, John"=>"12345"} 

解释:

s         # (\"Doe, John\",12345) 
s[1..-2]       # remove bracket => \"Doe, John\",12345 
.gsub('"', '')     # remove double quote => Doe, John,12345 
.reverse.sub(',', '|').reverse # make the last , into | => Doe, John|12345 
.split('|')      # split the string to array => ["Doe, John", "12345"] 
Hash[*s]       # make the array into hash => {"Doe, John"=>"12345"} 
0

你应该使用情况scan尚且如此,split

"(\"Doe, John\",12345)"[1...-1] 
.scan(/(?<=")[^"]*(?=")|[^,"]+/) 
# => ["Doe, John", "12345"] 
相关问题