10

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]]
11
  • without using eval or reg ex, gsub, etc. so what you want to do it with? Commented Jun 24, 2013 at 0:25
  • is there a simple way to do it? Commented Jun 24, 2013 at 0:26
  • 1
    i think eval is the most simple way, if you worry about security, check the string with regex to make sure. but seems you don't want both. Commented Jun 24, 2013 at 0:29
  • 1
    Why are you trying to avoid eval? How much simpler can it be than eval("[[1, 2], [3, 4], [5, 6]]")? Commented Jun 24, 2013 at 0:29
  • I have been told that 'eval' is a bad idea unless you really have to. Commented Jun 24, 2013 at 0:32

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

9

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]]  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.