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

时间:2020-03-05 18:46:07  来源:igfitidea点击:

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

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

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]

解决方案

回答

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

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闭合括号的计数。然后仅当计数等于零时才对逗号进行分割。

回答

创建一个使用字符串和整数偏移量并"读取"数组的递归函数。也就是说,让它返回一个数组或者字符串(已读取)以及指向数组后的整数偏移量。例如:

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

yourFunc(s, 1) # returns ['this', 'is'] and 11.
yourFunc(s, 2) # returns 'this' and 6.

然后,我们可以使用另一个提供偏移量0的函数来调用它,并确保结束偏移量是字符串的长度。

回答

笑一下:

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

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

回答

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

回答

我们也可以将其视为几乎JSON。如果字符串确实只是字母(如示例中所示),那么它将起作用:

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

如果他们可以有任意字符([],除外),则需要更多一点:

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