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.
ENV.each_key{|name| block}
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.
The value returned is ENV
.
# create environment variablesENV["G"] = "Google"ENV["N"] = "Netflix"ENV["A"] = "Apple"ENV["A"] = "Amazon"ENV["M"] = "Meta"ENV["FOO"] = ""# get access to the name of environment variablesENV.each_key{|name| puts "#{name} length = #{name.length}"}
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.