How to invert a hash in Ruby

Overview

A hash can be inverted using the invert method. It converts the hash by making each key-value inverted.

Syntax

hash.invert()

Parameters

hash: This is the hash value that we want to invert.

Return value

The value returned is a new hash with original key-value pairs inverted.

Code example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
# invert hashes
# and print results
puts h1.invert
puts h2.invert
puts h3.invert
puts h4.invert

Explanation

  • Lines 2-5: We create some hash.
  • Lines 9-12: The hash key-value pairs were inverted using the invert method. We print the results to the console.

Free Resources