SteveO7
SteveO7

Reputation: 2460

Pull array from inside a Ruby string

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

Upvotes: 0

Views: 67

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

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

Upvotes: 0

Chuck
Chuck

Reputation: 237060

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.

Upvotes: 2

karthikr
karthikr

Reputation: 99630

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.

Upvotes: 3

Related Questions