Rails string split every other "."

Advertisements

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?

>Solution :

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"]

Leave a ReplyCancel reply