4

How do I split string such as:

aaaaa
bbbb

aaaaa
ccccccc

aaa
rrrrt

into an array using blank lines as delimiter?

2
  • 1
    What exactly do you want the result to be? Commented Jan 28, 2019 at 12:59
  • Even though you have selected an answer you should edit your question to address @Tiw's question. The answer is not just for your benefit, so the question needs to be clear to all current and future readers. Commented Jan 28, 2019 at 17:42

1 Answer 1

8

Well, with String#split

'aaaaa bbbb'.split
=> ["aaaaa", "bbbb"]

split(pattern=nil, [limit]) → an_array

Divides str into substrings based on a delimiter, returning an array of these substrings.

[...]

If pattern is nil, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ' ' were specified.

UPDATE:

To split on empty line, you can use /\n{2,}/ pattern. It also handles paragraphs separated with more than one empty line:

a = <<END
aaaaa
bbbb


aaaaa
ccccccc

aaa
rrrrt
END

a.split(/\n{2,}/)
=> ["aaaaa\nbbbb", "aaaaa\nccccccc", "aaa\nrrrrt\n"]
Sign up to request clarification or add additional context in comments.

4 Comments

multiline, though? And they want to split by paragraphs, not by lines even.
ah, with corrected formatting, it's a different question
If you replace 'bbbb' with 'bbbb\n' (edge condition) in above your example, how code will deal with it?
You could also split by /^\n+/ which preserves the trailing newlines on the non-empty lines.

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.