2015-08-22 63 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"] 
相關問題