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.
ENV.key(value)
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.
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.
# clear default environment variablesENV.clear# create some environment variablesENV["secret_name"] = "secret"ENV["secret_token"] = "secret"ENV["private_key"] = "code_sync_456"ENV["foo"] = "123"ENV["bar"] = "123"# use the key() methodputs ENV.key("123") # fooputs ENV.key("secret") # secret_nameputs ENV.key("hello") # nilputs ENV.key("code_sync_456") # private_key
key()
method to get the keys of some values passed as parameters to the key()
method. Then we print these keys to the console.