Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
env
invert
communitycreator
method

How to use the invert method in Ruby

okwudili onyejiaku

Overview

The invert method in Ruby inverts the names and values of environment variables. The names take the position of the values, and vice versa. A hash returns when the switch takes place.

Syntax

ENV.invert
Inverting values and names

Return value

This method returns a hash of inverted environment variables names and values.

Code

# Clearing the default environment variables
ENV.clear

# Creating some environment variables
ENV["user_secret"] = "233lsdl323klsdr"
ENV["private_key"] = "123456ksdktjskdjs"
ENV["session_id"] = "ksdt323sl34w2"

# Printing all environment variables
ENV.each_pair{|name, value| puts "#{name} = #{value}"}

# Inverting all variables
puts ENV.invert
Inverting environment variables

Explanation

  • Line 2: We clear all environment variables.
  • Lines 5–7: We create some environment variables.
  • Line 10: We print all the environment variables.
  • Line 13: We invert the environment variables using the invert method. Then, we print the results to the console.

RELATED TAGS

ruby
env
invert
communitycreator
method
RELATED COURSES

View all Courses

Keep Exploring