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

时间:2021-11-25 20:22:15

I have a string with an array of arrays inside:

我有一个字符串,里面有数组:

"[[1, 2], [3, 4], [5, 6]]"

Can I convert this to the array of arrays, without using eval or a regular expression, gsub, etc.?

我可以不使用eval或正则表达式gsub等将其转换为数组吗?

Can I make turn it into:

我能把它变成:

[[1, 2], [3, 4], [5, 6]]

2 个解决方案

#1


21  

How about the following?

以下呢?

require 'json'
arr = JSON.parse("[[1, 2], [3, 4], [5, 6]]") # => [[1, 2], [3, 4], [5, 6]]
arr[0] # => [1, 2]

#2


9  

The same can be done using Ruby standard libaray documentation - YAML:

使用Ruby标准libaray文档也可以这样做——YAML:

require 'yaml'

YAML.load("[[1, 2], [3, 4], [5, 6]]")
 # => [[1, 2], [3, 4], [5, 6]]  

#1


21  

How about the following?

以下呢?

require 'json'
arr = JSON.parse("[[1, 2], [3, 4], [5, 6]]") # => [[1, 2], [3, 4], [5, 6]]
arr[0] # => [1, 2]

#2


9  

The same can be done using Ruby standard libaray documentation - YAML:

使用Ruby标准libaray文档也可以这样做——YAML:

require 'yaml'

YAML.load("[[1, 2], [3, 4], [5, 6]]")
 # => [[1, 2], [3, 4], [5, 6]]