Testing for existence with “blank?”

May 15, 2009

I know, I know, all ruby posts should be about slightly new takes on testing paradigms or other amazing best practices, but sometimes I think we skip the basiscs. Today it’s blank?.

ActiveSupport, the Rails extensions to ruby’s standard library introduce the method blank?. It’s pretty handy, and I think people tend to take it for granted without realizing exactly what its semantics are. blank? is handy if you want to treat an empty string, array, or hash as false.

Here’s a slightly haphazard table showing nil?, empty?, and blank? all work.

Input nil? empty? blank?
” “ FALSE FALSE TRUE
nil TRUE ERROR TRUE
1 FALSE ERROR FALSE
0 FALSE ERROR FALSE
“hi” FALSE FALSE FALSE
[] FALSE TRUE TRUE
[ [] ] FALSE FALSE FALSE
[ nil ] FALSE FALSE FALSE
[ 1 ] FALSE FALSE FALSE
true FALSE ERROR FALSE
false FALSE ERROR TRUE
{} FALSE TRUE TRUE
{1=>2} FALSE FALSE FALSE

So if you want a flexible way of testing whether something exists, blank? will often give you what you want. I’m sure that was just thrilling!

Entry Filed under: Uncategorized. Tags: , .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


AdamSanderson

del.icio.us

Feeds

Pages

 

May 2009
M T W T F S S
« Apr   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031

Archives

Blogroll

Meta