Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

env
ruby
communitycreator

What is the key?(name) method 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 key?() method is used to check whether an environment variable, passed to it as a parameter, exists or not. If it exists, it returnstrue and false otherwise.

Note: The method above is different from the key() method that returns the name of the first environment variable with the value passed to it as an argument.

Syntax

ENV.key?(name)
Syntax to check if an Environment Variable exists Using key() method

Parameter

We pass name as a parameter to this function. This is the name of the environment variable to be checked.

Return value

It returns true if the environment variable exists, otherwise, false.

Example

# clear default environment variables
ENV.clear
# create some environment variables
ENV["secret_name"] = "secret"
ENV["secret_token"] = "123"
ENV["private_key"] = "server123"
ENV["foo"] = "1"
ENV["bar"] = "0"
# use the key() method
puts ENV.key?("secret_name") # true
puts ENV.key?("secret") # false
puts ENV.key?("secret_name") # true
puts ENV.key?("bar") # true
Check if an Environment Variable exists using the key?() method

Explanation

  • Line 2: We clear all the default values of the environment variables using the clear method.
  • Lines 5–9: We create a new set of environment variables.
  • Lines 12–15: We use the key?() method to check if some environment variables exist or not. Next, we use puts to print the results 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