What is the each_key{} method of ENV in Ruby?

Overview

The each_key{} method of the environmental variable class, ENV, yields each environment variable name. This is otherwise known as the key. This means we can get hold of the name of each environment variable on our system and use it as required.

Syntax

ENV.each_key{|name| block}

Parameters

This method takes two parameters:

  • name: This is each environment variable’s name yielded by the each_key{} method.

  • block: This block gives us access to each environment variable’s name.

Return value

The value returned is ENV.

Example

# create environment variables
ENV["G"] = "Google"
ENV["N"] = "Netflix"
ENV["A"] = "Apple"
ENV["A"] = "Amazon"
ENV["M"] = "Meta"
ENV["FOO"] = ""
# get access to the name of environment variables
ENV.each_key{|name| puts "#{name} length = #{name.length}"}

Explanation

  • Line 2–7: We create some environment variables.
  • Line 10: We use each_key{} to yield each environment variable’s name, thus giving us access to them. Then, we print each name’s length to the console.

Note: There are a few extra environment variables in the output we did not declare. These are predefined and already exist in the code.