I'd do it like this:
ary = [
"Lorem ipsum dolor sit amet.\nVestibulum laoreet erat id quam.",
"Lorem ipsum dolor sit amet.\nVestibulum laoreet erat id quam.\n"
]
puts ary.map{ |a|
a.scan(/.+$/).map{ |s| "<p>#{s}</p>" }
}
# >> <p>Lorem ipsum dolor sit amet.</p>
# >> <p>Vestibulum laoreet erat id quam.</p>
# >> <p>Lorem ipsum dolor sit amet.</p>
# >> <p>Vestibulum laoreet erat id quam.</p>
Both strings are returned the same way.
Regular expressions are not a magic wand you can wave to fix every problem. They have their uses, but too many people think that they're the right tool for most of their problems, and they're not. Also, people think that the more complex the pattern, the more likely it is that it'll fix the problem, but instead the complexity provides more places for junk to squish out, so keep them simple.
This code:
a.scan(/.+$/).map{ |s| "<p>#{s}</p>" }
Relies on String's scan
to look through a string and return all "\n" terminated lines. If the line doesn't end with "\n" it gets returned also because it's the final part of the string. scan
returns an array of matches, so, in this particular situation, that'd be an array of string fragments terminated by the EOL with a possible trailing string-fragment.
Pass those through a map
to embed the string-fragment inside <p>...</p>
and you're done.
An alternate way to accomplish the same thing is to take advantage of String's gsub
with a block:
puts ary.map{ |a|
a.gsub(/.+$/) { |s| "<p>#{s}</p>" }
}
# >> <p>Lorem ipsum dolor sit amet.</p>
# >> <p>Vestibulum laoreet erat id quam.</p>
# >> <p>Lorem ipsum dolor sit amet.</p>
# >> <p>Vestibulum laoreet erat id quam.</p>
For each instance that matches the pattern, gsub
will pass the matched text to the block. From there it's another simple string interpolation.