String into Array

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

Why do that? It looks like YAML.

The solution is an hack.

You use the method scan of the String Class:

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

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(/[,[ ,]]/)

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

1 Like