Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Thanks

like image 913
Splashlin Avatar asked Dec 04 '22 13:12

Splashlin


2 Answers

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"
like image 189
Peter Avatar answered Dec 23 '22 02:12

Peter


Split and join is another technique:

s = "   a   b   c   "
s.split(' ').join(' AND ')
# => "a AND b AND c"

This has the advantage of ignoring leading and trailing whitespace that Peter's RE does not:

s = "   a   b   c   "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "

Removing whitespace

s.split(' ').join('')
# or
s.delete(' ')  # only deletes space chars
like image 43
glenn jackman Avatar answered Dec 23 '22 00:12

glenn jackman