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

前端 未结 5 2263
粉色の甜心
粉色の甜心 2020-12-16 21:04

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 w         


        
5条回答
  •  感情败类
    2020-12-16 21:54

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

提交回复
热议问题