13
Difference between .nil?, .empty?, .bank?, .present? and .any? Ruby Syntax Tips Henry Le

Different between .nil?, .empty?, .bank?, .present? and .any?

Embed Size (px)

Citation preview

Difference between .nil?, .empty?, .bank?, .present? and .any?

Ruby Syntax Tips Henry Le

.nil?

It is a Ruby method.

It can be used on any objects and will return true if the object is “null”.

.nil? examples

nil.nil? = true ( “Only the object nil responds true to .nil?” – RailsAPI )

anthing_else.nil? = false

.empty?It is a Ruby method.

Can be used on strings, arrays and hashes and will return true if their lengths are zero.

Running .empty? on something that is nil will throw a NoMethodError.

.empty? examples[].empty? = true

{}.empty? = true

"".empty?= true

" ".empty? = false

nil.empty? => “NoMethodError: undefined method `empty?' for nil:NilClass"

.blank?It is a Rails method (in ActiveSupport).

Operate on any object as well as work like .empty? on strings, arrays and hashes.

It also evaluates true on strings which are non-empty but contain only whitespace.

.blank? examplesnil.blank? = true

" ".blank? = true

"\n\t\t".blank? = true

[" “].blank? = false

[nil].blank? = false

.present?

It is a Rails method (in ActiveSupport).

It is vice versa from .blank?

!obj.blank? == obj.present?

.present? examplesnil.present? = false

false.present? = false

true.present? = true

[].present? = false

[“"].present? = true

[nil].present?

.any?

Pass each elements of the collection to the given block the returns true if the block ever returns a value other than false or nil.

.any? examples[nil, false].any? = false

We can customise the condition to return true:

[nil, false].any? { |w| w == false } = true

%w{ant bear cat}.any? { |word| word.length >= 3 } = true

.present? vs .any?

[nil, false].present? = true

[nil, false].any? = false

Conclusion