What is the ENV.fetch() method in Ruby?

Overview

The fetch() method of the ENV class fetches or finds an environment variable. It takes the environment variable’s name and returns the value of this environment variable.

Syntax

ENV.fetch(name)

Parameters

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

Return value

The value returned is the value of the environment variable that was fetched.

Example

# create some environment variables
ENV["A"] = "Apple"
ENV["M"] = "Meta"
ENV["G"] = "Google"
# fetch some environment variables
puts ENV.fetch("A")
puts ENV.fetch("G")
puts ENV.fetch("M")

Explanation

  • Lines 2–4: We create some environment variables.
  • Lines 7–9: We fetch the environment variables we created. The values returned are printed to the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources