Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split string into an array using blank lines as delimiter in ruby?

How do I split string such as:

aaaaa
bbbb

aaaaa
ccccccc

aaa
rrrrt

into an array using blank lines as delimiter?

like image 773
mila002 Avatar asked Jan 26 '23 19:01

mila002


1 Answers

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"]
like image 96
mrzasa Avatar answered Jan 29 '23 19:01

mrzasa