Travis Su
Travis Su

Reputation: 709

Extract string in a array of strings, split it and put into a new array in Ruby?

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.

Upvotes: 1

Views: 83

Answers (1)

Cyzanfar
Cyzanfar

Reputation: 7146

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).

Upvotes: 3

Related Questions