I find myself repeatedly looking for a clear definition of the differences of nil?
, blank?
, and empty?
in Ruby on Rails. Here's the closest I've come:
blank?
objects are false, empty, or a whitespace string. For example,""
," "
,nil
,[]
, and{}
are blank.nil?
objects are instances of NilClass.empty?
objects are class-specific, and the definition varies from class to class. A string is empty if it has no characters, and an array is empty if it contains no items.
Is there anything missing, or a tighter comparison that can be made?
present?
. Which is becauseblank?
returns true for an empty array. – Kris:nil?
is defined on::Kernel
and overridden on::NilClass
, while:empty?
is implemented separately on many classes (natively on::String
,::Array
,::Hash
, and non-natively on other classes like::Set
from stdlib and::ActiveRecord::Relation
from rails). So:nil?
is available in all subclasses of::Object
and also in every class that includes::Kernel
by itself, where:empty?
must be implemented or included specifically in your classes. – rewrittennil
concept start here. – totymedli[1] pry(main)> [].blank? => true
– Michael