Home > Software engineering >  Rails string split every other "."
Rails string split every other "."

Time:11-15

I have a bunch of sentences that I want to break into an array. Right now, I'm splitting every time \n appears in the string.

@chapters = @script.split('\n')

What I'd like to do is .split ever OTHER "." in the string. Is that possible in Ruby?

CodePudding user response:

You could do it with a regex, but I'd start with a simple approach: just split on periods, then join pairs of substrings:

s = "foo. bar foo. foo bar. boo far baz. bizzle"
s.split(".").each_slice(2).map {|p| p.join "." }
# => => ["foo. bar foo", " foo bar. boo far baz", " bizzle"]

CodePudding user response:

This question provides multiple solutions to what you want to accomplish - Ruby ReGex Split at nth new line.

  • Related