0

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

This will execute arbitrary code. If anyone but you has any influence over the contents of x, they can potentially control your computer. It is generally not a great idea.
@Chuck You are right. Just using eval is not a good idea. I was editing my answer to use Bindings on top of eval. Thanks
AFAIK it is quite difficult to come up with a binding that is not potentially exploitable, so I would still not feel good about doing this.
I'll use Chuck's answer but yours is very interesting. What is eval used for if it is so unsafe?
@SteveO7, If it is your string, then it is safe to use eval. There is a family of eval functions in ruby that are used to do advanced stuff.
|
2

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

Comments

0

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

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.