Split a string with multiple delimiters in Ruby

Mark picture Mark · Jun 1, 2011 · Viewed 12.2k times · Source

Take for instance, I have a string like this:

options = "Cake or pie, ice cream, or pudding"

I want to be able to split the string via or, ,, and , or.

The thing is, is that I have been able to do it, but only by parsing , and , or first, and then splitting each array item at or, flattening the resultant array afterwards as such:

options = options.split(/(?:\s?or\s)*([^,]+)(?:,\s*)*/).reject(&:empty?);
options.each_index {|index| options[index] = options[index].sub("?","").split(" or "); }

The resultant array is as such: ["Cake", "pie", "ice cream", "pudding"]

Is there a more efficient (or easier) way to split my string on those three delimiters?

Answer

mabako picture mabako · Jun 1, 2011

What about the following:

options.gsub(/ or /i, ",").split(",").map(&:strip).reject(&:empty?)
  • replaces all delimiters but the ,
  • splits it at ,
  • trims each characters, since stuff like ice cream with a leading space might be left
  • removes all blank strings