if data.nil? || data.blank?
inform_user
end
I've seen the above code often enough lately that I thought a brief post was in order to inform/remind folks that
blank? is all you need. Here's a script/console session proving just that.
$ script/console
Loading development environment (Rails 2.3.5)
>> data = nil
=> nil
>> data.nil?
=> true
>> data.blank?
=> true
Thus, we can eliminate the first half of the conditional expression.
if data.blank?
inform_user
end
Now, if you find you want to check !
blank? but you prefer to express your conditional checks positively instead of negatively, you can use
present?.
if !data.blank?
show_it
end
becomes
if data.present?
show_it
end
Using
blank? and
present? enables clearer and more concise conditionals, a benefit not only now but every time someone reads the code.
2 comments:
This is just within Rails, right? I didn't know about present?, and that could have been useful to me a couple of times... Thanks!
Jeremy, yes, blank? and present? are part of Rails.
Post a Comment