Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string with multiple delimiters in Ruby

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?

like image 979
Mark Avatar asked Jun 01 '11 20:06

Mark


2 Answers

As "or" and "," does the same thing, the best approach is to tell the regex that multiple cases should be treated the same as a single case:

options = "Cake or pie, ice cream, or pudding"
regex = /(?:\s*(?:,|or)\s*)+/
options.split(regex)
like image 147
Andrew Grimm Avatar answered Sep 21 '22 05:09

Andrew Grimm


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
like image 29
mabako Avatar answered Sep 19 '22 05:09

mabako