What is the replace() method of the ENV class in Ruby?

Overview

The replace() method replaces all the environment variables present. It is similar to the clear method. It replaces all variables with new environment variables that it takes as a Hash. This Hash is the parameter that it takes.

Syntax

ENV.replace(hash)
Syntax for the replace() method in Ruby

Parameters

hash: This is a hash that is passed to the replace() method. The name/value pairs of this hash replace all the environment variables present.

Return value

The value returned is the ENV.

Code example

# print current environment variables
puts "PREVIOUS ENVIRONMENT VARIABLES: \n"
ENV.each_pair{|name, value| puts "#{name} = #{value}"}
# replace all environment variables with replace()
ENV.replace("c" => "cat", "token" => "123", "secret" => "323dsdf")
# reprint all environment variables
puts "\nCURRENT ENVIRONMENT VARIABLES: \n"
ENV.each_pair{|name, value| puts "#{name} = #{value}"}

Explanation

  • Line 3: We use the each_pair{} method and print the current environment variables.
  • Line 6: We use the replace() method and replace all environment variables present with new ones.
  • Line 10: We reprint the same environment variables as the ones in line 3.