16

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

and much more, but nothing works.

2
  • possible duplicate of Ruby : Trim New blank lines Commented Sep 7, 2011 at 19:14
  • 2
    it's not a duplicate. that title is very misleading Commented Sep 7, 2011 at 19:16

5 Answers 5

29

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
Sign up to request clarification or add additional context in comments.

1 Comment

It depends on the definition of elegant; one might argue that the more explicit solution is the more elegant! :)
13

squeeze (or squeeze!) does just that - without a regex.

str.squeeze("\n")

1 Comment

@janechii hello \n is not ` hello followed by a blank line, it is " hello" followed by a line ending.
4

Replace multiple newlines with a single one:

fixedstr = str.gsub(/\n\n+/, "\n") 

or

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

Comments

3

You could try to replace all occurrences of 2 or more line breaks with just one:

my_string.gsub(/\n{2,}/, '\n')

Comments

0

Originally

some_string = some_string.gsub(/\n/,'')

Updated

some_string = some_string.gsub(/^$\n/,'')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.