marcamillion
marcamillion

Reputation: 33775

How do I detect if a line in a string has nothing but line carriage(s)?

I have a string that has multiple lines. What I am doing is checking each line for specific characteristics and then treating them accordingly.

One characteristic is if the line begins with a + or a -. That works just fine.

Another characteristic is if it contains nothing but a \n, but I am not sure how to check for that.

Here is an example of a string:

 "+        end\n",
 " \n",
 "-      # Specifies a many-to-many relationship with another class. This associates two classes via an\n",

I have some simple checks that detect the first & last line, that look like this <% if line.start_with?("-") %>.

But not quite sure how to check to see if the line ONLY has a (or multiple) \n. Note that other lines can have \n in that line and should NOT trigger this condition (like the first & last line).

The key thing is if the line contains ONLY line carriage returns \n.

Edit 1

Note that I am not trying to remove those lines. I am simply looking for a regex or perhaps a built in ruby function that will help me easily identify the lines that fit the above condition.

Upvotes: 1

Views: 131

Answers (1)

Ilya
Ilya

Reputation: 13487

You are possibly looking for a String#strip, which returns a copy of string with leading and trailing whitespace removed:

def if_empty?(string)
  string.strip.empty?
end

if_empty?(" \n\n\n\n")
=> true

Upvotes: 3

Related Questions