Splashlin Splashlin - 10 months ago 82
Ruby Question

Replace white space with AND in ruby

I have someone entering a form with some string input. What I need to do is replace any white space in the string with " AND " (no quotes). What's the best way to do this?

Also, how would I go about doing this if I wanted to remove all the whitespace in the string?


Answer Source

to replace with and:

s = 'this has   some     whitespace'
s.gsub! /\s+/, ' AND '

=> "this AND has AND some AND whitespace"

to remove altogether:

s = 'this has   some     whitespace'
s.gsub! /\s+/, ''

=> "thishassomewhitespace"