How to get the length of environment variables in Ruby
Overview
The length of environment variables is the total number of all environment variables present. In other words, this is the count of all environment variables. We can use the length property to get this number.
Syntax
ENV.length
Syntax for length property of ENV in ruby
Return value
The value returned is an integer that represents the number of environment variables present.
Code example
# Getting the length of default variablesputs "#{ENV.length}" # 6# Clearing all environment variablesENV.clear# Getting the length of current variablesputs "#{ENV.length}" # 0# Creating some environment variablesENV["secret_name"] = "secret"ENV["secret_token"] = "secret"ENV["private_key"] = "code_sync_456"ENV["foo"] = "123"ENV["bar"] = "123"# Reprinting the length of environment variablesputs "#{ENV.length}" # 5
Explanation
- Line 2: We print the length of environment variables present.
- Line 5: We clear all variables using the
clearmethod. - Line 8: We print the new length of environment variables to the console.
- Lines 11–15: We print some new environment variables to the console.
- Line 18: We print the new length to the console.