如何将带括号的Ruby字符串转换为数组?

我想将以下字符串转换为数组/嵌套数组:

str = "[[this, is],[a, nested],[array]]" newarray = # this is what I need help with! newarray.inspect # => [['this','is'],['a','nested'],['array']] 

你会得到你想要的YAML。

但是你的字符串有点问题。 YAML希望逗号背后有空格。 所以我们需要这个

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

码:

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

笑一笑:

  ary = eval("[[this, is],[a, nested],[array]]".gsub(/(\w+?)/, "'\\1'") ) => [["this", "is"], ["a", "nested"], ["array"]] 

免责声明:你绝对不应该这样做,因为eval是一个糟糕的主意,但它很快并且如果你的嵌套数组无效则会产生抛出exception的有用副作用

您也可以将其视为几乎为JSON。 如果字符串真的只是字母,就像你的例子中那样,那么这将起作用:

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

如果他们可以有任意字符(除了[],),你还需要更多:

 JSON.parse("[[this, is],[a, nested],[array]]".gsub(/, /,",").gsub(/([^\[\]\,]+)/,'"\1"')) 

看起来像一个基本的解析任务。 通常,您要采用的方法是使用以下通用算法创建递归函数

 base case (input doesn't begin with '[') return the input recursive case: split the input on ',' (you will need to find commas only at this level) for each sub string call this method again with the sub string return array containing the results from this recursive method 

这里唯一一个棘手的部分是将输入分成单个’,’。 您可以为此编写一个单独的函数,它将扫描字符串并保持openbrackets的计数 – 目前为止看到的closedbrakets。 然后只有在计数等于零时才用逗号分割。

创建一个带有字符串和整数偏移量的递归函数,并“读取”一个数组。 也就是说,让它返回一个数组或字符串(它已读取)和一个指向数组后面的整数偏移量。 例如:

 s = "[[this, is],[a, nested],[array]]" yourFunc(s, 1) # returns ['this', 'is'] and 11. yourFunc(s, 2) # returns 'this' and 6. 

然后,您可以使用另一个提供偏移量0的函数调用它,并确保完成偏移量是字符串的长度。