rubystringruby-1.9.2

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


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.


Solution

  • 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.