Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

How to convert the ENV to hash in Ruby

okwudili onyejiaku

Overview

The to_h method can be used to convert the ENV, which contains all environment variables, into a hash. A hash contains key-value pairs.

Syntax

ENV.to_h
Convert an ENV to Hash Syntax

Parameters

None.

Return value

The value returned is a hash containing each environment variable in the form of key/value pairs.

Example

# clear default 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"

# convert to hash
ourHash = ENV.to_h

# print new hash
puts ourHash 
puts ourHash.class
Convert ENV to hash in Ruby

Explanation

  • Line 2: We clear all default environment variables.
  • Lines 5–9: We create new environment variables.
  • Line 12: We convert the ENV to a hash and store the hash value in the variable ourHash.
  • Line 15: We print the hash value to the console.
  • Line 16: We use to_h to create the type of class and print it to the console.

RELATED TAGS

ruby
communitycreator
RELATED COURSES

View all Courses

Keep Exploring