On Dec 14, 10:48 am, Max Williams <toastkid.willi... / gmail.com> wrote: > I want to add a slightly hacky feature into my boolean mysql search > which lets users write 'foo and bar', which is then translated into > '+foo +bar' (ie both 'foo' and 'bar' must be present) before being > passed to the search. Similarly, "foo and bar and snafu" should be > translated into "+foo +bar +snafu". > > I'm sure there must be a simple way to do this but i'm new to ruby and > have got bogged down in loads of nested ifs and exceptions already. > > Can anyone help with an elegant solution? I feel like there's a more elegant one-pass regexp, but I haven't the time to think much on it. So: phrases = [ "foo", "foo or bar", "foo and bar", "foo and bar and snafu" ] phrases.each{ |phrase| result = phrase.dup :go while result.gsub!( /\+?(\S+)\s*and\s*(\S+)/, '+\\1 +\\2' ) puts "#{phrase.inspect} -> #{result.inspect}" } #=> "foo" -> "foo" #=> "foo or bar" -> "foo or bar" #=> "foo and bar" -> "+foo +bar" #=> "foo and bar and snafu" -> "+foo +bar +snafu"