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

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

    You could also treat it as almost-JSON. If the strings really are only letters, like in your example, then this will work:

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

    If they could have arbitrary characters (other than [ ] , ), you'd need a little more:

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

提交回复
热议问题