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 hashesh1 = {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 resultsputs h1.invertputs h2.invertputs h3.invertputs h4.invert
Explanation
- Lines 2-5: We create some hash.
- Lines 9-12: The hash key-value pairs were inverted using the
invertmethod. We print the results to the console.