What is the ENV[name] method in Ruby?

Overview

In Ruby, the ENV[name] method is used to return the value for the environment variable name. If it does not exist, it returns nothing. If the name is invalid, it throws an error.

Syntax

ENV[name]

Parameters

  • name: This is the name of the environment variable we want to get the value of.

Return value

It returns the value of the environmental variable name. If it’s not found or if it doesn’t exist, it returns nothing.

Code example

# create some environment variables
ENV["G"] = "Google"
ENV["N"] = "Netflix"
ENV["A"] = "Apple"
ENV["A"] = "Amazon"
ENV["M"] = "Meta"
ENV["FOO"] = ""
# get values of some environment variables
puts ENV["G"]
puts ENV["M"]
puts ENV["FOO"]
puts ENV["A"]

Explanation

  • Line 2–7: We create some environment variables.
  • Line 10–13: We print the values of the environment variables to the console.

Free Resources