How to delete an environment variable in Ruby
Overview
We use the delete() method to delete an environment variable in Ruby. Environment variables are used to share configuration options between all the programs in our system.
Syntax
ENV.delete(env_name)
Parameter value
env_name: This is the name of the environment variable that we want to delete.
Return value
The delete() method returns the value of the environment variable that is deleted.
Code example
# create some environment variablesENV["name"] = "OKWUDILI"ENV["role"] = "DEVELOPER"ENV["language"] = "RUBY"ENV["nothing"] = "nothing"# get all environment variablesputs "All envrionment variables: \n"for entry in ENV doputs "#{entry}"end# delete an environment variable# and print returned valuedeletedValue = ENV.delete("nothing")puts "Deleted value = #{deletedValue}"# Reprint environment variablesfor entry in ENV doputs "#{entry}"end
Code explanation
- Lines 2–5: We create some environment variables.
- Line 9: We print out the environment variables we have, together with their values, using the
forloop. This is done before deleting an environment variable. - Line 15: We delete an environment variable called
nothingand store the value inside the variable calleddeletedValue. - Line 16: We print out the deleted value of the environment variable.
- Line 19: We reprint the environment variables once more. Note that the environment variable
nothingis no longer in the list.