How to get environment variables in the form of an array in Ruby

Overview

The to_a method can be used to return the environment variable class, ENV, to an array. It returns an array containing the name/value pairs of each environment variable.

Syntax

ENV.to_a
Syntax for slice() method of ENV

Parameter

None.

Return value

An array that contains objects of two attributes is returned, with a name/value pair for each.

Code example

# clear all 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"
# reprint length of environment variables
puts "#{ENV.to_a}"

Explanation

  • Line 2: We cleared default environment variables.
  • Line 5–9: We create new environment variables.
  • Line 12: We use the to_a method, we were able to get the array containing 2-element arrays of name/value pair of each environment variable. And then we printed our result.

Free Resources