Checking Null or empty values in Ruby

n Ruby, you can easily check whether a variable is nil or an empty value for different data types, including strings, arrays, and hashes. Here are some common ways to perform null and empty checks:

Checking for nil

# Check if a variable is nil
if my_variable.nil?
  puts "The variable is nil."
else
  puts "The variable is not nil."
end

Checking for Empty Strings

if my_string.empty?
   puts "The string is empty."
 else
   puts "The string is not empty."
 end

Checking for Empty Arrays

# Check if an array is empty
if my_array.empty?
  puts "The array is empty."
else
  puts "The array is not empty."
end

Checking for Empty Hashes

# Check if a hash is empty
if my_hash.empty?
  puts "The hash is empty."
else
  puts "The hash is not empty."
end

Using blank?

In Ruby, the blank? method is not a built-in method, but it is often used in Ruby on Rails applications. It is a custom method for checking whether a string is either nil, empty, or contains only whitespace characters. The blank? method is handy for checking if a string has meaningful content.

str = "   " # A string with only whitespace characters

if str.blank?
  puts "String is blank"
else
  puts "String is not blank"
end

In a Ruby on Rails application, you can use blank? not only for strings but also for other data types like arrays, hashes, and more. It’s a part of Rails’ ActiveSupport library, and it simplifies checking for empty or nil values in various data types. For plain Ruby, without Rails, you would need to define your own blank? method or use the nil? and .empty? methods as shown in the previously

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *