Split string without removing delimiter

Yup, scan it:

'a; b; c;'.scan(/[^;]*;/)
#=> ["a;", " b;", " c;"]

You could get rid of the excess whitespace by tacking on map(&:strip) after, but it's probably not needed here.

Note that this is very rudimentary, and something like a string literal in the SQL with a semicolon in it will break this. (E.g. select * from stuff where name = ";";.)


When using ActiveRecord::Base.connection.execute you don't need to include the semicolon in the first place.

Also, another way to split without removing the delimiter is to use groups as shown in the following example:

"a;b;c".split(/;/)   # => ["a", "b", "c"]

"a;b;c".split(/(;)/) # => ["a", ";", "b", ";", "c"]