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 | ||||||||
---|---|---|---|---|---|---|---|---|
Ruby | Rails | |||||||
Object | String, Array, Hash | Enumerable | Numeric | Object | ||||
if condition !! operator | nil? | empty? | any? | zero? | blank? | present? | ||
nil | false | true | NoMethodError | NoMethodError | NoMethodError | true | false | |
false | false | false | NoMethodError | NoMethodError | NoMethodError | true | false | |
true | true | false | NoMethodError | NoMethodError | NoMethodError | false | true | |
0 | true | false | NoMethodError | NoMethodError | true | false | true | |
1 | true | false | NoMethodError | NoMethodError | false | false | true | |
"" | true | false | true | NoMethodError | NoMethodError | true | false | |
" " | true | false | false | NoMethodError | NoMethodError | true | false | |
[] | true | false | true | false | NoMethodError | true | false | |
[nil] | true | false | false | false | NoMethodError | false | true | |
{} | true | false | true | false | NoMethodError | true | false | |
{a: nil} | true | false | false | true | NoMethodError | false | true |
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.