nil?
As expected, you can use nil?
to check if an object is nil. It returns true
only when the object is nil
. For all other values, it returns false
.
nil_object = nil
nil_object.nil? # true
data = Hash.new
data.nil? # false
empty?
You can use this method on strings, arrays, and hashes. It returns true
in the following cases:
- String doesn’t have any characters, i.e.
str.length == 0
- Array doesn’t contain any elements, i.e.
arr.length == 0
- Hash doesn’t have any key-value pairs, i.e.
hash.length == 0
[].empty? # true
''.empty? # true
{}.empty? # true
nil.empty? # NoMethodError
false.empty? # NoMethodError
It’s important to note that an object can be empty and not nil
. For example:
names = []
names.empty? # true
names.nil? # false
If you try to call .empty?
on a nil
or any other object, Ruby throws NoMethodError
.
nil.empty?
# undefined method `empty?' for nil:NilClass (NoMethodError)
blank?
This is a nice syntactic sugar implemented in Rails. An object is blank if it’s nil
, false
, or empty
. For example, nil
,false
, ''
, []
, {}
are all blank.
You can think of blank?
as a shorthand for the following code.
!val || val.empty?
Here's how it works for various values.
nil.blank? # true
false.blank? # true
''.blank? # true
[].blank? # true
{}.blank? # true
In addition, .blank?
returns true if a string contains only whitespace characters.
" ".blank? # true
Rails also provides present?
, which is the opposite of blank?
. It checks if the value is not blank
.
That's a wrap. I hope you liked this article and you learned something new.
As always, if you have any questions or feedback, didn't understand something, or found a mistake, please leave a comment below or send me an email. I reply to all emails I get from developers, and I look forward to hearing from you.
If you'd like to receive future articles directly in your email, please subscribe to my blog. If you're already a subscriber, thank you.