What is the hash.shift method in Ruby?

Overview

The shift method of a hash is used to return the first hash entry of a hash.

Syntax

hash.shift

Parameters

This method does not take any parameters.

Return value

This method returns a 2-element array that contains the removed key and value.

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"}
# use the shift method
puts "#{h1.shift}"
puts "#{h2.shift}"
puts "#{h3.shift}"
puts "#{h4.shift}"

Explanation

  • Lines 2 to 5: We create several hashes.
  • Lines 8 to 11: We print the results using the shift to return the first hash entry in a 2-element array containing the key and value

Free Resources