String into Array


#1

I want to get a Array from String;
ex:
“[1,2,3,4,{a:1}]” --> [1,2,3,4,{:a => 1}],
dont use eval()


#2

Why do that? It looks like YAML.


#3

The solution is an hack.

You use the method scan of the String Class:
https://ruby-doc.org/core-2.4.1/String.html#method-i-scan

```
"This is the bee's knees".scan /\w/
#=> ["T", "h", "i", "s", "i", "s", "t", "h", "e", "b", "e", "e", "s", "k", "n", "e", "e", "s"]
```

scan return parts of a sentence base on a pattern. And in this example the pattern /\w/ mean every chars of the alphabet.


#4

string_data = “[1,2,3,4,{a:1}]”
First perform the split with ‘,’ ‘[’ and ‘]’ then shift the result to get string format data into array format.
array_data = string_data.split(/[,[ ,]]/)
array_data.shift

output the array_data => [“1”, “2”, “3”, “4”, “{a:1}”]