What is ENV.key() in Ruby?

Overview

key() is a method of the ENV class in Ruby. The ENV class stands for environment variables. Environment variables are used to store secrets, variables, or configurations that we don't want the public to know in our applications. They could be a database URL, API keys, and so on.

The form of an environment variable is a key/value pair. The key() method takes a value as its parameter. It then gets the name of the first environment variable with such a value. We should use the key() method when we want to get the key or the name of an environment variable with a particular value.

Syntax

ENV.key(value)
Syntax for the key() value

Parameters

The key() method accepts only one argument, the value. With this argument, the key() method returns its key.

For example, there is an environment variable called language and has a value that is ruby. When the key() method is called and ruby is passed as an argument, then language will be returned.

Return value

They first key whose value is equal to the argument value is returned. When no such key is present, a nil or nothing is returned.

Example

# clear default environment variables
ENV.clear
# create some environment variables
ENV["secret_name"] = "secret"
ENV["secret_token"] = "secret"
ENV["private_key"] = "code_sync_456"
ENV["foo"] = "123"
ENV["bar"] = "123"
# use the key() method
puts ENV.key("123") # foo
puts ENV.key("secret") # secret_name
puts ENV.key("hello") # nil
puts ENV.key("code_sync_456") # private_key

Explanation

  • Line 2: We clear the default environment variables.
  • Line 5–9: We create some new environment variables.
  • Line 12–15: We use the key() method to get the keys of some values passed as parameters to the key() method. Then we print these keys to the console.

Free Resources