What is ENV.each_value{} in Ruby?

Overview

The each_value{} method of an ENV yields or accesses the value of each environment variable. When it yields each value, we can decide to do anything with it, such as print it, push it to an array, and so on.

Syntax

ENV.each_value{|value|block}

Parameters

value: This is the value of each environment variable yielded by the each_value{} method.

block: This takes each value of the environment variable, value, and allows us to do anything with it.

Example

# create some environment variables
ENV["1"] = "One"
ENV["payment_key"] = "skdmj234ksdu9"
ENV["token_key"] = "3234"
# create an empty array
arr = []
# access each value of environment variables
# and push to an array
ENV.each_value{
|value| arr.push(value)
}
# print array
puts "#{arr}"

Explanation

  • Line 2–4: We create some environment variables coupled with some system environment variables.
  • Line 7: We create an empty array, arr, that will contain all the values of every environment variable.
  • Line 11: We use the each_value{} method. We are able to access all values of the environment variables. Then, we push each value to the array we created previously.
  • Line 18: We print the array to the console.

Free Resources