Ruby Remove Empty Lines from String

Ruby remove empty lines from string

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

How do I remove blank elements from an array?

There are many ways to do this, one is reject

noEmptyCities = cities.reject { |c| c.empty? }

You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).

Remove blank rows from CSV file

Three simple steps:

data = File.read('data.csv')                       # Read the file
cleaned = data.gsub(/^$\n/, '') # Remove blank lines, from [1]
File.open('out.csv', 'w') { |f| f.write(cleaned) } # Write the cleaned data

[1] Remove empty lines from string

How do I delete empty strings in array

The problem with your code is explained by Ed S.

Otherwise, you can do

products.reject! { |s| s.nil? || s.strip.empty? }

Why do you need to test nil? first? Let's check few lines.

nil.strip
# NoMethodError: undefined method `strip' for nil:NilClass
" ".strip
# => ""

Now, with a different order, what the code does if the object is a string, and then if it is nil.

"  ".strip || "  ".nil?
# => ""
nil.strip || nil.nil?
# NoMethodError: undefined method `strip' for nil:NilClass
# Oh you don't want that to happen, do you?

This means you don't want to call strip.empty? when your object is nil.

And as you know, when you have a || b, if a is truthy (i.e. not nil nor false), b will never be called.

You test first if the string is nil ; if it is, you don't need to check the right part (so you won't get a undefined method error) and the object will be removed from your products list.

Ignore empty captures when splitting string

When splitting with a regex containing capturing groups, consecutive matches always produce empty array items.

Rather than switch to a matching approach, use

arr = arr.reject { |c| c.empty? }

Or any other method, see How do I remove blank elements from an array?

Else, you will have to match the substrings using a regex that will match the deilimiters first and then any text that does not start the delimiter texts (that is, you will need to build a tempered greedy token):

arr = s.scan(/(?x)\*{2}|[*\n.]|(?:(?!\*{2})[^*\n.])+/)

See the regex demo.

Here,

  • (?x) - a freespacing/comment modifier
  • \*{2} - ** substring
  • | - or
  • [*\n.] - a char that is either *, newline LF or a .
  • | - or
  • (?:(?!\*{2})[^*\n.])+ - 1 or more (+) chars that are not *, LF or . ([^*\n.]) that do not start a ** substring.

How do I split string into an array using blank lines as delimiter in ruby?

Well, with String#split

'aaaaa bbbb'.split
=> ["aaaaa", "bbbb"]

split(pattern=nil, [limit]) → an_array

Divides str into substrings based on a delimiter, returning an array of these substrings.

[...]

If pattern is nil, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ' ' were specified.

UPDATE:

To split on empty line, you can use /\n{2,}/ pattern. It also handles paragraphs separated with more than one empty line:

a = <<END
aaaaa
bbbb

aaaaa
ccccccc

aaa
rrrrt
END

a.split(/\n{2,}/)
=> ["aaaaa\nbbbb", "aaaaa\nccccccc", "aaa\nrrrrt\n"]


Related Topics



Leave a reply



Submit