The other day I wanted to break up a search string into its constituent parts. We’re not supporting any fancy operators, but we did want to allow phrases to be specified in double quotes. It’s an easy enough operation, but I googled to see if anyone was offering a particularly efficient way to do that in ruby.

Nothing came up and since I’ve not posted in a while I thought I’d offer it for anyone else in that situation.

def split_params(params)
  # Find all phrases enclosed in quotes and pull
  # them into a flat array of phrases
  phrases = params.scan(/"(.*?)"/).flatten

  # Remove those phrases from the original string
  left_over = params.gsub(/"(.*?)"/, "").squeeze(" ").strip

  # Break up the remaining keywords on whitespace
  keywords = left_over.split(/ /)

  # Return one single array of key phrases
  keywords + phrases
end