Replace space with AND in ruby

I have someone going into a form with some string input. What I need to do is replace any empty space in the string "AND" (without quotes). What is the best way to do this?

Also, how do I do this if I want to remove all spaces in a string?

thanks

+4
source share
3 answers

to replace with and:

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

delete at all:

 s = 'this has some whitespace' s.gsub! /\s+/, '' => "thishassomewhitespace" 
+12
source

Separation and merging is another way:

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

This has the advantage that ignoring spaces in leading and trailing spaces that Peter RE does not support:

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

Delete spaces

 s.split(' ').join('') # or s.delete(' ') # only deletes space chars 
+4
source

use gsub method to replace spaces

  s = "ajeet soni" => "ajeet soni" s.gsub(" "," AND ") => "ajeet AND soni" 
+1
source

Source: https://habr.com/ru/post/1299291/


All Articles