Topic: .empty? vs .blank? for strings (answered)

Is there a difference between these two to check if a string is empty -




I'm tempted to use ''.empty? since it works both in ruby and therefore in rails whereas ''.blank?  seems to only work in rails.  Any idea why the ''.blank? method was introduced to rails and if I should be using that instead?

Last edited by sthapit (2008-04-17 21:11:07)

Re: .empty? vs .blank? for strings (answered)

According to:

.blank? is a method on Object while .empty? is a method on String. Blank appears to do the same thing as .empty when called on a string, but is more versatile as it also acts the same way on Hashes, Arrays, Strings, and nilable objects.

Re: .empty? vs .blank? for strings (answered)

rephrasing what jbartels said, and making a key point:

.blank? basically performs a .nil? and .empty?

So, it is useful with dealing with string that might be nil, because nil.empty? will raise an exception.

Re: .empty? vs .blank? for strings (answered)

got it thanks smile  i'll be using .blank? from now on!

Last edited by sthapit (2008-04-17 21:11:27)

Re: .empty? vs .blank? for strings (answered)

While I realize this post is almost 5 years old; it still returns high in the Google results so I wanted to add something here.

.empty? and .blank? do not exhibit quite the same behavior on strings

.empty? does a length check; so if we have a = '' then it is a zero length string and thus .empty? will return true
Now if instead we have a = '   ' we now a a 3 length string and thus .empty? will return false

.blank? is doing some type of white space checking, so it will return true in BOTH of the cases just shown for .empty?

Which of these is the correct behavior will vary based on your individual needs, but I wanted to point this out since it is a variance and could have unintended consequences.