tbone
tbone

Reputation: 882

How do I convert a string to an array of arrays?

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.?

Can I make turn it into:

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

Upvotes: 10

Views: 2466

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

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

require 'yaml'

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

Upvotes: 9

vee
vee

Reputation: 38645

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]

Upvotes: 21

Related Questions