I have a string that contains an array;
"["item1","item2","item3"]"
Is there a slick Ruby way to convert it to this;
["item1","item2","item3"]
Ruby has an eval function
irb(main):003:0> x = '["item1","item2","item3"]'
=> "[\"item1\",\"item2\",\"item3\"]"
irb(main):004:0> eval(x)
=> ["item1", "item2", "item3"]
irb(main):005:0>
It might not be safe to use eval, so you might want to consider using Binding too.
x, they can potentially control your computer. It is generally not a great idea.eval is not a good idea. I was editing my answer to use Bindings on top of eval. ThanksIt really depends on the string. A string can't actually contain an array — it can just contain some text that can be parsed into an array given an appropriate parser.
In this case, your string happens to be a valid JSON representation of an array, so you can just do:
JSON.parse("[\"item1\",\"item2\",\"item3\"]")
And you'll get that array with those strings.
If you write
str = '"["item1","item2","item3"]"'
#=> "\"[\"item1\",\"item2\",\"item3\"]\""
or
str =<<_
"["item1","item2","item3"]"
_
#=> "\"[\"item1\",\"item2\",\"item3\"]\""
or
str = %q{"["item1","item2","item3"]"}
#=> "\"[\"item1\",\"item2\",\"item3\"]\""
then you could write
str.scan(/[a-z0-9]+/)
#=> ["item1", "item2", "item3"]