Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
key
env
communitycreator

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

okwudili onyejiaku

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
How to check if a certain key exists in our environment variable

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.

RELATED TAGS

ruby
key
env
communitycreator
RELATED COURSES

View all Courses

Keep Exploring