Home > database >  How do I get Ruby's String Split Method to Include Newlines in the Output?
How do I get Ruby's String Split Method to Include Newlines in the Output?

Time:01-29

There's this code right here:

thing = "Stuff.\nHello!"
result = thing.split(" ")
# ^Is equal to ["Stuff.", "Hello!"] despite the delimiter being a single space instead of a newline

How do I make it so that the newline is included, making the result var equal to ["Stuff.\n", "Hello!"] instead?

I'm using Ruby 1.9.2. For those who are curious, I need to know this for the sake of a word-wrapping algorithm that replaces line-break tags with newlines.

CodePudding user response:

You can use a regexp with a positive look-behind assertion:

thing = "Stuff.\nHello!"
thing.split(/(?<=\s)/)
#=> ["Stuff.\n", "Hello!"]

The positive look-behind assertion (?<=pat) ensures that the preceding characters match pat, but doesn’t include those characters in the matched text.

CodePudding user response:

One could simply use String#lines.

"Stuff.\nHello!".lines    #=> ["Stuff.\n", "Hello!"]
"Stuff.\nHello!\n".lines  #=> ["Stuff.\n", "Hello!\n"]
  • Related