0

I have this string that I'm trying split into nested arrays:

x = '{type:paragaph|class:red|content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]}'
x << '{type:image|class:grid|content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]}'

This so far:

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}

successfully divides it into:

[
  ["type:paragaph", "class:red", "content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]"],
  ["type:image", "class:grid", "content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]"]
]

I'm trying to add an additional map:

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}.map {|m| m[0].split(/\:\s*(?=[^\[\]]*(?:\[|$))/)}

which returns:

[["type", "paragaph"], ["type", "image"]] 

however I am after this instead:

[
  [['type','paragaph'], ['class','red'], ['content',['[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]']],
  [['type','image'], ['class','grid'], ['content','[id:1|title:image1][id:2|title:image2][id:3|title:image3]']]
]

The map appears to be applying itself to the whole 2nd level array instead of each element inside it. What am I doing wrong here?

1 Answer 1

1

In the second map you your are splitting only the first element instead of spliting every element with a map

x.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}.map {|m| m.map {|n| n.split(/\:\s*(?=[^\[\]]*(?:\[|$))/)}}

Also you could clean it up a little extracting the regex into a variable

regex = /\|\s*(?=[^\[\]]*(?:\[|$))/

x.scan(/\{(.*?)\}/).map {|m| m[0].split(regex)}.map {|m| m.map {|n| n.split(regex)}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.