Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Ruby string with brackets to an array?

Tags:

arrays

ruby

I would like to convert the following string into an array/nested array:

str = "[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]
like image 670
Mike Farmer Avatar asked Sep 01 '08 20:09

Mike Farmer


2 Answers

You'll get what you want with YAML.

But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this

str = "[[this, is], [a, nested], [array]]"

Code:

require 'yaml'
str = "[[this, is],[a, nested],[array]]"
### transform your string in a valid YAML-String
str.gsub!(/(\,)(\S)/, "\\1 \\2")
YAML::load(str)
# => [["this", "is"], ["a", "nested"], ["array"]]
like image 69
Wieczo Avatar answered Oct 06 '22 01:10

Wieczo


You could also treat it as almost-JSON. If the strings really are only letters, like in your example, then this will work:

JSON.parse(yourarray.gsub(/([a-z]+)/,'"\1"'))

If they could have arbitrary characters (other than [ ] , ), you'd need a little more:

JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"'))
like image 31
glenn mcdonald Avatar answered Oct 05 '22 23:10

glenn mcdonald