Remove multiple spaces and new lines inside of String

RubyString

Ruby Problem Overview


Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.

Ruby Solutions


Solution 1 - Ruby

check out Rails squish method:

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

Solution 2 - Ruby

To illustrate Rubys built in squeeze:

string.gsub("\n", ' ').squeeze(' ')

Solution 3 - Ruby

The simplest way would probably be

s = "Hello, my\n       name is Michael."
s.split.join(' ') #=> "Hello, my name is Michael."

Solution 4 - Ruby

Try This:

s = "Hello, my\n       name is Michael."
s.gsub(/\n\s+/, " ")

Solution 5 - Ruby

my_string = "Hello, my\n       name is Michael."
my_string = my_string.gsub( /\s+/, " " )

Solution 6 - Ruby

this regex will replace instance of 1 or more white spaces with 1 white space, p.s \s will replace all white space characters which includes \s\t\r\n\f:

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

Similarly for only carriage return

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

First replace all \n with white space, then use the remove multiple white space regex.

Solution 7 - Ruby

Use String#gsub:

s = "Hello, my\n       name is Michael."
s.gsub(/\s+/, " ")

Solution 8 - Ruby

Use squish
currency = " XCD"
str = currency.squish
 str = "XCD" #=> "XCD"

Solution 9 - Ruby

You can add just the squish method (and nothing else) to Ruby by including just 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKreekiView Question on Stackoverflow
Solution 1 - RubysocjopataView Answer on Stackoverflow
Solution 2 - RubysteenslagView Answer on Stackoverflow
Solution 3 - RubyKoraktorView Answer on Stackoverflow
Solution 4 - RubyanushaView Answer on Stackoverflow
Solution 5 - Rubyfl00rView Answer on Stackoverflow
Solution 6 - RubyAliView Answer on Stackoverflow
Solution 7 - RubyNikolaView Answer on Stackoverflow
Solution 8 - Rubyvikas palView Answer on Stackoverflow
Solution 9 - RubyConvincibleView Answer on Stackoverflow