Delete some lines and new lines inside String

Suppose we have a line like this:

Hello, my\n name is Michael. 

How can I remove this new line and put these spaces after that into one inside the line to get this?

 Hello, my name is Michael. 
+81
string ruby
Aug 18 '11 at 11:50
source share
9 answers

check out the Rails squish method:

http://apidock.com/rails/String/squish

+156
Aug 18 '11 at 12:02
source share

To illustrate Rubys built in compression :

 string.gsub("\n", ' ').squeeze(' ') 
+33
Aug 18 '11 at 12:08
source share

The easiest way -

 s = "Hello, my\n name is Michael." s.split.join(' ') #=> "Hello, my name is Michael." 
+17
Aug 18 '11 at 11:56
source share

this regular expression will replace an instance of 1 or more white spaces with 1 space, ps \s will replace all space characters that include \s\t\r\n\f :

 a_string.gsub!(/\s+/, ' ') 

Similarly for carriage return only

 str.gsub!(/\n/, " ") 

Replace all \n with a space first, then use removing multiple space.

+4
Aug 18 '11 at 11:56
source share
 my_string = "Hello, my\n name is Michael." my_string = my_string.gsub( /\s+/, " " ) 
+4
Aug 18 '11 at 11:57
source share

Use String # gsub :

 s = "Hello, my\n name is Michael." s.gsub(/\s+/, " ") 
+3
Aug 18 '11 at 11:56
source share

Try the following:

 s = "Hello, my\n name is Michael." s.gsub(/\n\s+/, " ") 
+3
Apr 30 '14 at 13:03
source share
 Use squish currency = " XCD" str = currency.squish str = "XCD" #=> "XCD" 
+1
Dec 20 '16 at 5:24
source share

You can add only the squish method (and nothing more) in Ruby by including only this Ruby Facet:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/squish.rb

 require 'facets/string/squish' 

Then use

 "my \n string".squish #=> "my string" 

Doesn't require Rails.

0
Dec 19 '18 at 14:24
source share



All Articles