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

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

    Looks like a basic parsing task. Generally the approach you are going to want to take is to create a recursive function with the following general algorithm

    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
    

    The only slighlty tricky part here is splitting the input on a single ','. You could write a separate function for this that would scan through the string and keep a count of the openbrackets - closedbrakets seen so far. Then only split on commas when the count is equal to zero.

提交回复
热议问题