Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

invert
ruby
hash
communitycreator

How to invert a hash in Ruby

okwudili onyejiaku

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
Inverting hashes in Ruby

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.

RELATED TAGS

invert
ruby
hash
communitycreator
RELATED COURSES

View all Courses

Keep Exploring