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."
  puts "The variable is not nil."

Checking for Empty Strings

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

Checking for Empty Arrays

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

Checking for Empty Hashes

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

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"
  puts "String is not blank"

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 *