How to check if there are no environment variables in Ruby

Overview

We can check if there are no environment variables using the empty? property of the ENV class. It returns true if the environment variables are available, otherwise, it returns a false.

Syntax

ENV.empty?

Return values

The value returned is a Boolean. It returns true if there are environment variables available, otherwise, it returns `false.

Code example

# create some environment variables
ENV["G"] = "Google"
ENV["N"] = "Netflix"
ENV["A"] = "Apple"
ENV["A"] = "Amazon"
ENV["M"] = "Meta"
ENV["FOO"] = ""
# check if empty
puts ENV.empty? # false
# clear environment variables
ENV.clear
# check if empty
puts ENV.empty? # true

Code explanation

  • Lines 2 to 7: We create some environment variables.
  • Line 10: We check if there are environment variables present and print the result.
  • Line 13: We clear all environment variables.
  • Line 16: We recheck if the environment variables exist and print the result to the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources