[ACCEPTED]-How to split string across new lines and keep blank lines?-split

Accepted answer
Score: 59

I'd recommend using lines instead of split for this 12 task. lines will retain the trailing line-break, which 11 allows you to see the desired empty-line. Use 10 chomp to clean up:

"aaaa\nbbbb\n\n".lines.map(&:chomp)
[
    [0] "aaaa",
    [1] "bbbb",
    [2] ""
]

Other, more convoluted, ways 9 of getting there are:

"aaaa\nbbbb\n\n".split(/(\n)/).each_slice(2).map{ |ary| ary.join.chomp }
[
    [0] "aaaa",
    [1] "bbbb",
    [2] ""
]

It's taking advantage 8 of using a capture-group in split, which returns 7 the split text with the intervening text 6 being split upon. each_slice then groups the elements 5 into two-element sub-arrays. map gets each 4 two-element sub-array, does the join followed 3 by the chomp.

Or:

"aaaa\nbbbb\n\n".split(/(\n)/).delete_if{ |e| e == "\n" }
[
    [0] "aaaa",
    [1] "bbbb",
    [2] ""
]

Here's what split is returning:

"aaaa\nbbbb\n\n".split(/(\n)/)
[
    [0] "aaaa",
    [1] "\n",
    [2] "bbbb",
    [3] "\n",
    [4] "",
    [5] "\n"
]

We 2 don't see that used very often, but it can 1 be useful.

Score: 15

You can supply a negative argument for the 4 second parameter of split to avoid stripping 3 trailing empty strings;

"aaaa\nbbbb\n\n".split(/\n/, -1)

Note that this will 2 give you one extra empty string compared 1 to what you want.

Score: 4

You can use the numeric argument, but IMO 3 it's a bit tricky since (IMO) it's not quite 2 consistent with what I'd expect, and AFAICT 1 you'd want to trim the last null field:

jruby-1.6.7 :020 > "aaaa\nbbbb\n\n".split(/\n/, -1)[0..-2]
 => ["aaaa", "bbbb", ""] 

More Related questions