Ruby and Rails object checking methods cheat sheet

Comparing basic object checking methods of ruby and Rails.

For a novice in ruby and Rails it is not obvious which object checking methods come from where and what methods better to use for what and in which situation. There are many blog posts and StackOverflow questions about this topic (personal I inspired by A concise explanation of nil v. empty v. blank in Ruby on Rails Ask Question). That is why I decide to organize this information for myself in the current blog post, and I would be glad if it will be useful for someone else.

Basic object checking methods

Methods
RubyRails
ObjectString, Array, HashEnumerableNumericObject
if condition
!! operator
nil?empty?any?zero?blank?present?
nilfalsetrueNoMethodErrorNoMethodErrorNoMethodErrortruefalse
falsefalsefalseNoMethodErrorNoMethodErrorNoMethodErrortruefalse
truetruefalseNoMethodErrorNoMethodErrorNoMethodErrorfalsetrue
0truefalseNoMethodErrorNoMethodErrortruefalsetrue
1truefalseNoMethodErrorNoMethodErrorfalsefalsetrue
""truefalsetrueNoMethodErrorNoMethodErrortruefalse
" "truefalsefalseNoMethodErrorNoMethodErrortruefalse
[]truefalsetruefalseNoMethodErrortruefalse
[nil]truefalsefalsefalseNoMethodErrorfalsetrue
{}truefalsetruefalseNoMethodErrortruefalse
{a: nil}truefalsefalsetrueNoMethodErrorfalsetrue

Rails helper methods with object checking

presence

Returns the receiver if it's present otherwise returns nil. object.presence is equivalent to:

object.present? ? object : nil

try

Invokes the public method whose name goes as first argument just like public_send does, except that if the receiver does not respond to it the call returns nil rather than raising an exception.

try!

Same as try, but raises a NoMethodError exception if the receiver is not nil and does not implement the tried method.

Final thoughts

It is obvious, when working with Rails it is better to use Rails object checking methods. In that case, ruby object checking methods must be used only if you what to emphasize some special meaning of a certain expression.