Presence in Rails

One thing that might not be immediately obvious is that an empty string in a conditional in Ruby will return true. See for yourself:

irb(main):006:0> puts "Whoa" if ""
(irb):6: warning: string literal in condition

The same holds true for other empty things — say, arrays:

irb(main):008:0> puts "See?" if []
=> nil

Pure Ruby will let you call .empty? (on some methods — it’s not standard on Object though!), but code like this is silly and it’s easy to forget:

irb(main):003:0> puts "We have some meaningful value" if str and !str.empty?
=> nil

But Rails makes this easy for us. Rails extends Object to add a present? method. present? is literally defined as !blank?, which is almost always what I actually want to check for: it’s not nil, or “blank”, like a string that’s just whitespace, or empty constructs like [] or {}:

irb(main):009:0> nil.blank?
=> true
irb(main):010:0> [].present?
=> false
irb(main):011:0> "     ".present?
=> false
irb(main):012:0> 0.present?
=> true

Hardly an earth-shattering development, but it’s a handy tool that seems underused.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>