How to check if all the environment variables are empty in Ruby
Overview
We use the ENV class to store environment variables. These environment variables can be secrets and configurations we want to keep private. We can check if all these variables are empty by using the empty? property.
Syntax
ENV.empty?
Return value
The empty? function returns true when there are no environment variables. Otherwise, it returns false.
Example
The following piece of code completes the picture and shows the example with its output:
# create some environment variablesENV["payment_key"] = "323selfdsd34"ENV["authorization_key"] = "123456788"# check if ENV is emptyputs ENV.empty? # false# print all environment variablesENV.each_pair{|name, value| puts "#{name} = #{value}"}# clear all variablesENV.clear# check if ENV is emptyputs ENV.empty? # true
Explanation
- Line 2 and 3: We create two environment variables on our own.
- Line 6: We check if
ENVis empty. - Line 9: We use the
each_pair{}method that gives us access to each environment variable name and value. - Line 12: We clear all environment variables using the
clearmethod. - Line 15: We check if
ENVis empty once more.