【问题标题】:How do I convert a Ruby string with brackets to an array?如何将带括号的 Ruby 字符串转换为数组?
【发布时间】:2010-09-07 11:51:34
【问题描述】:

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

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

newarray = # this is what I need help with!

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

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    你会得到你想要的 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"]]
    

    【讨论】:

    • 非常感谢您!我快要疯了,试图弄清楚这一点。 :)
    【解决方案2】:

    笑一笑:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        【解决方案4】:

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

        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。然后仅在计数等于 0 时以逗号分隔。

        【讨论】:

          【解决方案5】:

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

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-01
            • 2019-01-24
            • 1970-01-01
            • 2016-05-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多