Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple newlines in a row with one newline using Ruby

I have a script written in ruby. I need to remove any duplicate newlines (e.g.)

\n \n \n 

to

\n 

My current attempt worked (or rather not) using

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

Which gave me no change to the output. What am I doing wrong?

like image 454
Macha Avatar asked Mar 31 '09 13:03

Macha


2 Answers

This works for me:

#!/usr/bin/ruby  $s = "foo\n\n\nbar\nbaz\n\n\nquux";  puts $s  $s.gsub!(/[\n]+/, "\n");  puts $s 
like image 140
Chas. Owens Avatar answered Oct 08 '22 12:10

Chas. Owens


Use the more idiomatic String#squeeze instead of gsub.

str = "a\n\n\nb\n\n\n\n\n\nc" str.squeeze("\n") # => "a\nb\nc" 
like image 35
gioele Avatar answered Oct 08 '22 12:10

gioele