1

Suppose I have a array of strings like this:

arr = ["\n<start>\n<exposition> <conflict> <escape> <conclusion>\t;\n", 
       "\n<exposition>\n<bad-guy> <insane-plan>\t;\n",
       "\n<conflict>\n<friendly-meeting> <female-interest> <danger>\t;\n"]

I want to extract every string in the array, split it using \n as the delimiter, then put it back to an array like this:

newArr = ["<start>",
          "<exposition> <conflict> <escape> <conclusion>",
          "<exposition>",
          "<bad-guy> <insane-plan>",
          "<conflict>",
          "<friendly-meeting> <female-interest> <danger>"]

I'm new to Ruby I tried to use for loop to iterate the array but it seems will eliminate all the Unix line ending then I have no delimiters to split the strings, and in the strings in arr they also have couple of extra characters \t; to remove.

5
  • one way, not very pretty. arr.map { |s| s.scan(/\n(\<.*?\>)\n/) + s.scan(/(\<.*\>)\t\;\n/) }.flatten Commented Oct 28, 2017 at 4:00
  • @sagarpandya82 kinda confusing whats inside the scan() ..... could you explain that to me? Commented Oct 28, 2017 at 4:03
  • Please wait for someone to answer (with explanation). The regex inside scan() is grabbing characters according to your specification. If you're unfamiliar with regex (sorry if you are) check out: regexone.com as a starter. Commented Oct 28, 2017 at 4:09
  • @sagarpandya82 your solution is pretty good why not answer it? Commented Oct 28, 2017 at 4:42
  • Please be more specific about the treatment of semicolons. For example, what should be the return value for the array ["<a;b>;<c>;\n<d>;\t<e>"]? Commented Oct 28, 2017 at 6:02

1 Answer 1

3

You can simply achieve this with some regex:

arr.join.split /[\n\t;]+/

Here I'm joining the array of strings into one string and splitting it according to multiple conditions (newline, tab, and semicolon).

Sign up to request clarification or add additional context in comments.

1 Comment

@Cyzenfar what if there is two ;\n in here? for example like "["\n<conflict>\n<friendly-meeting> <female-interest> <danger>;\n;\n"] , then the output should be ["<conflict>", "<friendly-meeting> <female-interest> <danger>", ""]

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.