Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is the each_key{} method of ENV in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The each_key{} method of the environmental variable class, ENV, yields each environment variable name. This is otherwise known as the key. This means we can get hold of the name of each environment variable on our system and use it as required.

Syntax

ENV.each_key{|name| block}

Parameters

This method takes two parameters:

  • name: This is each environment variable’s name yielded by the each_key{} method.

  • block: This block gives us access to each environment variable’s name.

Return value

The value returned is ENV.

Example

# create environment variables
ENV["G"] = "Google"
ENV["N"] = "Netflix"
ENV["A"] = "Apple"
ENV["A"] = "Amazon"
ENV["M"] = "Meta"
ENV["FOO"] = ""
# get access to the name of environment variables
ENV.each_key{|name| puts "#{name} length = #{name.length}"}
Access environment variable names using each_key{}

Explanation

  • Line 2–7: We create some environment variables.
  • Line 10: We use each_key{} to yield each environment variable’s name, thus giving us access to them. Then, we print each name’s length to the console.

Note: There are a few extra environment variables in the output we did not declare. These are predefined and already exist in the code.

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring