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]]
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
tbone
  • 892
  • 1
  • 7
  • 17
  • without using eval or reg ex, gsub, etc. so what you want to do it with? – leonhart Jun 24 '13 at 00:25
  • is there a simple way to do it? – tbone Jun 24 '13 at 00: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. – leonhart Jun 24 '13 at 00:29
  • 1
    Why are you trying to avoid `eval`? How much simpler can it be than `eval("[[1, 2], [3, 4], [5, 6]]")`? – lurker Jun 24 '13 at 00:29
  • I have been told that 'eval' is a bad idea unless you really have to. – tbone Jun 24 '13 at 00:32
  • Also, I don't really know how to use reg ex yet (still learning), but am fine using it if I understand it – tbone Jun 24 '13 at 00:32
  • @stinkydiesel, I suggest using a different format if construction of that string is under your control. Like for example json so that its more readable and using JSON.parse() instead of using regex. But regex is undoubtedly powerful and if you say you are still learning then yes, absolutely continue with the learning. – vee Jun 24 '13 at 00:38
  • @vinodadhikary How is the string not already json? – jcsanyi Jun 24 '13 at 00:52
  • @jcsanyi, I guess that's why I used it in my proposed answer below :). I added a new vocabulary for the OP'er as he constrained his options to `eval`, `regex` and `gsub`. – vee Jun 24 '13 at 01:08
  • duplicate of http://stackoverflow.com/questions/4477127/ruby-parsing-a-string-representation-of-nested-arrays-into-an-array – Yuri Golobokov Jun 24 '13 at 03:32
  • @stinkydiesel, `eval` is the right tool for the job in this case. Only if the string is user input than it *could* be a bad idea. – Shoe Jun 24 '13 at 06:29

2 Answers2

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]
Mischa
  • 42,876
  • 8
  • 99
  • 111
vee
  • 38,255
  • 7
  • 74
  • 78
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]]  
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317