Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

env
ruby
communitycreator

What is the keep_if{} 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

In Ruby, the keep_if{} method gives us access to each environment variable as a 2-element array. It also deletes each environment variable that returns false or nil when used in the block. This means that any environment variable for which the block of keep_if{} that returns false is deleted.

Syntax

 ENV.keep_if{|name, value| block}

Parameters

  • name: This represents the name of each environment variable name.
  • value: This is the value representation of each environment variable.
  • block: This is a block that allows us to have access to the name and value of each environment variable. It is a conditional statement. If the environment variable is deleted, it returns false.

Return value

It returns an ENV.

Example

# clear default environment variables
ENV.clear
# create some environment variables
ENV["secret_name"] = "secret_name"
ENV["secret_token"] = "server_1234"
ENV["private_key"] = "code_sync_456"
# print environment names and values
ENV.each_pair{|name, value| puts "#{name} = #{value}"}
# using keep_if delete some environment variables
ENV.keep_if{|name, value| name.start_with?("s")}
# reprint all environment variables
puts "\n New Environment Variables:"
ENV.each_pair{|name, value| puts "#{name} = #{value}"}
Using the keep_if{} to delete some environment variables

Explanation

  • Line 2: We use the clear method to clear all default environment variables.
  • Line 5–7: We create some environment variables.
  • Line 10: We use the each_pair{} method to print the environment variables to the console.
  • Line 13: We use the keep_if{} method to delete some elements that returned false in its block.
  • Line 17: We use the each_pair{} method to print the environment variables to the console.

RELATED TAGS

env
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