bonhoffer
bonhoffer

Reputation: 1473

Testing string for no content

I want to send a message to a ruby string object that tests for no_content:

"".content? => false # same as .empty?
"   ".content? => false # same as .blank?
"\n\t".content? => false # new feature

Specifically, content? would pass true if there is anything a person could read there. I am going to monkey patch the String class to do this with a regular expression.

"\n\t\n\n".gsub(/[\n|\t]/,'').empty?

This gets me close, but I might be re-inventing the wheel and would like a more complete solution.

Upvotes: 2

Views: 147

Answers (3)

Michael Kohl
Michael Kohl

Reputation: 66837

Something like this?

class String
  def content?
    self !~ /\A\s*\z/
  end
end

"".content? #=> false
"   ".content? #=> false
"\n\t".content? #=> false
"foo".content? #=> true

Upvotes: 1

jimworm
jimworm

Reputation: 2741

strip it before checking.

"\n\t".strip.empty?

Upvotes: 2

rdvdijk
rdvdijk

Reputation: 4398

Check out present? in ActiveSupport.

Upvotes: 5

Related Questions