Programming
Ruby tip of the day
July 4, 2014
0

Hi folks!

Have you ever thought about removing new line “\n” and all whitespaces  from a string?

The magic we need is in  Ruby  “gsub” function:

" My string\n  ".gsub("\n","").strip

the first gsub removes all newline characters while the second one removes all whitespaces; so the result will be

 

Mystring

isn’t it simple?

If you want to remove only trailing and leading spaces, the above expression must be changed using Ruby “strip” function in the following way:

 

" My string\n ".gsub("\n","").strip

and the result will be

My string

So now start coding and remove all whitespaces!!

Enjoy!

Leave a Reply

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close