Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby remove empty lines from string

Tags:

string

ruby

How do i remove empty lines from a string? I have tried some_string = some_string.gsub(/^$/, "");

and much more, but nothing works.

like image 779
john-jones Avatar asked Sep 07 '11 19:09

john-jones


1 Answers

Remove blank lines:

str.gsub /^$\n/, ''

Note: unlike some of the other solutions, this one actually removes blank lines and not line breaks :)

>> a = "a\n\nb\n"
=> "a\n\nb\n"
>> a.gsub /^$\n/, ''
=> "a\nb\n"

Explanation: matches the start ^ and end $ of a line with nothing in between, followed by a line break.

Alternative, more explicit (though less elegant) solution:

str.each_line.reject{|x| x.strip == ""}.join
like image 55
Peter Avatar answered Sep 19 '22 01:09

Peter