Given the ruby code:
"aaaa\nbbbb\n\n".split(/\n/)
This outputs:
["aaaa", "bbbb"]
I would like the output to include the blank line indicated by \n\n — I want the result to be:
["aaaa", "bbbb", ""]
What is the easiest/best way to get this exact result?
I’d recommend using
linesinstead ofsplitfor this task.lineswill retain the trailing line-break, which allows you to see the desired empty-line. Usechompto clean up:Other, more convoluted, ways of getting there are:
It’s taking advantage of using a capture-group in
split, which returns the split text with the intervening text being split upon.each_slicethen groups the elements into two-element sub-arrays.mapgets each two-element sub-array, does thejoinfollowed by thechomp.Or:
Here’s what
splitis returning:We don’t see that used very often, but it can be useful.