How to know if a key is present in ENV in Ruby using has_key()

Overview

We can check if a certain key is present in our environment variables using the has_key() method in Ruby. This method is invoked on the ENV class.

Syntax

ENV.has_key(name)

Parameters

name: This is the name of each environment variable that we want to check to see if it is present.

Return value

The value returned is a Boolean. If the key exists, then true is returned. Otherwise, false is returned.

Example

# create some environment variables
ENV["platform"] = "Edpresso"
ENV["isBest"] = "true"
ENV["user_key"] = "1234skldks"
# check if some environment variables exist
puts ENV.has_key?("user_key") # true
puts ENV.has_key?("isBest") # true
puts ENV.has_key?("platform") # true
puts ENV.has_key?("foo") # false
puts ENV.has_key?("bar") # false

Explanation

  • Line 2–4: We create some environment variables.
  • Line 7–11: Using the has_key() method, we check if some environment variable names exist and then print the results to the console.

Free Resources