Splashlin
Splashlin

Reputation: 7585

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

Upvotes: 4

Views: 8428

Answers (3)

Ajeet Soni
Ajeet Soni

Reputation: 19

use gsub method for replacing whitespace

 s = "ajeet soni"

 => "ajeet soni" 

 s.gsub(" "," AND ")

 => "ajeet AND soni" 

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246837

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

Upvotes: 4

Peter
Peter

Reputation: 132247

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"

Upvotes: 12

Related Questions