What is the ENV.member?() method in Ruby?

Overview

The member?() method of the ENV class in Ruby tells us if there is an environment variable with the given name. The name is passed as a parameter to the member?() method.

Syntax

ENV.member?(name)
Syntax for the member?() method

Parameters

This method takes the parameter, name, which represents the name of the environment variable for which we want to check.

Return value

It returns a boolean value. It returns true if an environment variable with such name exists. Otherwise, it returns false.

Example

# clear default environment variables
ENV.clear
# create some environment variables
ENV["secret_name"] = "secret"
ENV["secret_token"] = "123"
ENV["private_key"] = "server123"
ENV["foo"] = "1"
ENV["bar"] = "0"
# use the key() method in driver code
env_name = ["secret_name", "secret", "secret_token", "bar"]
for i in 0..3 do
print(env_name[i], ": " , ENV.member?(env_name[i]), "\n")
end

Explanation

  • Line 2: We clear all present environment variables.
  • Line 5–9: We create some new environment variables.
  • Line 14: We use the member?(), along with some name as parameters. We check if some variables exists. Next, we print the results.

Free Resources