Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
env
reject
communitycreator

What is the ENV.reject{} method 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.

Answers Code

Overview

In Ruby, the reject{} method gives us access to the name and value of each environment variable as a 2-element array. It returns a Hash containing a value pair of environment variables that is determined by its block. If the block returns true, the value pair is added to the Hash returned. Otherwise, it ignores the pair.

Syntax

ENV.reject{|name, value| block}
Syntax for reject{} method

Parameters

name: This represents the name of each environment variable.

value: This is the value of the environment variable.

block: This is a condition that returns true or false for the name and value pair, depending on what is specified.

Return value

The value returned is a Hash of the value pair.

Example

# clear default environment variables]
ENV.clear
# create some new environment variables
ENV["foo"] = "one"
ENV["bar"] = "two"
ENV["bar_code"] = "123abc"
ENV["secret_code"] = "cba321"
# reject name/value pair that starts with "b"
puts ENV.reject { |name, value| name.start_with?('b') } # => {"foo"=>"0"}
Using the reject{} method in Ruby

Explanation

  • Line 2: We clear the environment variables present.
  • Line 5–8: We create some new environment variables.
  • Line 11: We use the reject{} method to reject the names of environment variables that start with "b", meaning they were not added to the Hash returned. Next, we print the value pairs added to the Hash.

RELATED TAGS

ruby
env
reject
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.

Answers Code
Keep Exploring