将字符串转换为元组,散列或数组

时间:2015-08-22 23:43:48

标签: arrays ruby hash

我有一个字符串:

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

我想将此字符串转换为元组("Doe, John",12345),哈希{"Doe, John" => 12345}或数组["Doe, John",12345]

我不确定如何将其拆分为2个元素"Doe, John"12345。我想避免使用regex。我无法使用split,因为我得到["(\"Doe", "John", "12345)"]

2 个答案:

答案 0 :(得分: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"}

答案 1 :(得分:0)

在这种情况下,您应该使用scan,而不是split

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