Ruby – Split string without removing delimiter

rubyruby-on-rails-3

I need to parse a file to get individual SQL statements and run them from rails controller.

I have the following code:

@sql_file = "#{RAILS_ROOT}/lib/evidence_interface_import.sql"   
@sql_stmts_array = File.read(@sql_file).split(";")  

@sql_stmts_array.each_with_index do |sql_stmt,s_index|
   ActiveRecord::Base.connection.execute(sql_stmt)
end

The split removes the ";" from the end of the SQLs. Is there a way not to remove the ";" and still split using ";".

Best Answer

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 = ";";.)