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

前端 未结 5 2264
粉色の甜心
粉色の甜心 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:56

    For a laugh:

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

    Disclaimer: You definitely shouldn't do this as eval is a terrible idea, but it is fast and has the useful side effect of throwing an exception if your nested arrays aren't valid

提交回复
热议问题