What is an ENV.size in Ruby?

Overview

We use the size property of the ENV class in Ruby to return the count of environment variables present. It is similar to the length property.

Syntax

ENV.size
Syntax for size property of ENV

Return value

The value returned is an integer that represents the total number of environment variables present.

Code example

# get size of default variables
puts "#{ENV.size}" # 6
# clear all environment variables
ENV.clear
# get size of current variables
puts "#{ENV.size}" # 0
# create some environment variables
ENV["secret_name"] = "secret"
ENV["secret_token"] = "secret"
ENV["private_key"] = "code_sync_456"
ENV["foo"] = "123"
ENV["bar"] = "123"
# reprint size of environment variables
puts "#{ENV.size}" # 5

Explanation

  • Line 2: We print the size or the number of environment variables present.
  • Line 5: We clear all variables using the clear method.
  • Line 8: We use the size property to print the number of environment variables to the console.
  • Line 11–15: We print new environment variables
  • Line 18: We reprint the new size of environment variables to the console.