Exploring present, presence and empty method in Ruby.
present Method:
present?
is a method provided by ActiveSupport, an extension to the Ruby core library.
It is commonly used to check if an object is not nil
and not empty.
It returns true
if the object has a value (not nil
and not empty), or false
otherwise.
str = "Hello, World!"
puts str.present? # Output: true
arr = []
puts arr.present? # Output: false
num = 0
puts num.present? # Output: true
nil_obj = nil
puts nil_obj.present? # Output: false
presence Method:
presence
is also a method provided by ActiveSupport.
It is used to return the object itself if it is present (not nil
or empty), and nil
otherwise.
This method is particularly useful when you want to return a default value or perform a fallback operation if the object is not present.
str = "Hello, World!"
puts str.presence # Output: "Hello, World!"
arr = []
puts arr.presence # Output: nil
num = 0
puts num.presence # Output: 0
nil_obj = nil
puts nil_obj.presence # Output: nil
empty Method:
empty?
is a built-in Ruby method available on certain objects such as strings, arrays, and hashes.
It is used to check if an object is empty, meaning it has no elements or has a length of zero.
The behavior of the empty?
method varies depending on the object type.
str = "Hello, World!"
puts str.empty? # Output: false
arr = []
puts arr.empty? # Output: true
hash = {}
puts hash.empty? # Output: true