Hash is a very common data structure used by Ruby developers. This article will discuss some important hash methods every Ruby developer should know.

Let’s start.

# fetch

Fetch is useful when the value against a specific key is needed. If a key is not found, an exception is raised. If a key is not found but a value against it is given, it will return that value.

1
2
3
4
5
6
7
8
9
10
11
12

h = {a: 500, b: 700}
h.fetch(:a)
=> 500
h.fetch(:b)
=> 700
h.fetch(:c)
KeyError (key not found: :c)
h.fetch(:c, 900)
=> 900

# flatten

When called on a hash, this method returns a new one-dimensional array. Optionally, it also takes an argument that tells this method of how deep is the flattening required.

1
2
3
4
5
6
7
8
9

h = {a: 1, b: 2, c: {d: 4, e: 5}}
h.flatten
=> [:a, 1, :b, 2, :c, {:d=>4, :e=>5}]
h = {a: 1, b: [2, 3]}
h.flatten
=> [:a, 1, :b, [2, 3]]
h.flatten(2)
=> [:a, 1, :b, 2, 3]

# include?

This method returns a value if the given key is present.

1
2
3

h = {a: 1, b: 3, c: 4}
h.include?(:a)
=> true

# merge

Merge is used to combine a set of given hashes into receiver hash.

1
2
3
4
5
6
7
8

h = {a: 1, b: 2}
h2 = {c: 3, d: 4}
h3 = {c: 5, f: 6}
h.merge(h2)
=> {:a=>1, :b=>2, :c=>3, :d=>4}
h.merge(h2, h3)
=> {:a=>1, :b=>2, :c=>5, :d=>4, :f=>6}

# select

This method returns a new hash containing the values that meet the condition specified in a block. This does not change the original hash.

1
2
3
4
5

h = {:a=>1, :b=>2, :c=>4, :d=>9}
h.select {|k, v| v > 2}
=> {:c=>4, :d=>9}
h
=> {:a=>1, :b=>2, :c=>4, :d=>9}

Use select! If you want to change the original hash.

# reject

This method returns a new hash eliminating the values that meet the condition specified in a block. This does not change the original hash.

1
2
3
4
5

h = {:a=>1, :b=>2, :c=>4, :d=>9}
h.reject {|k, v| v > 2}
=> {:a=>1, :b=>2}
h
=> {:a=>1, :b=>2, :c=>4, :d=>9}

Use reject! If you want to change the original hash.

# transform_values

This method runs the given block once for every value in the hash and returns a new hash with updated values.

1
2
3
4
5

h = {:a=>2, :b=>5, :c=>10}
h.transform_values {|v| v + 10 }
=> {:a=>12, :b=>15, :c=>20}
h
=> {:a=>2, :b=>5, :c=>10}

# dig

This returns the value of nested keys.

1
2
3

h = {:a=>{:b=>{:c=>2}}}
h.dig(:a, :b, :c)
=> 2

# with_indifferent_access

This method is particularly related to Ruby on Rails. In hash, a key can be of two types, string or symbol.

1
2
3
4
5
6
7
8
9
10
11
12
13

h = {a: 2, b: 5, c: 10}
h["a"]
=> nil
h[:a]
=> 2
require "active_support/core_ext/hash/indifferent_access"
=> true
h = {a: 2, "c": 3, d: 10}.with_indifferent_access
h["a"]
=> 2
h[:c]
=> 3

These are all methods that will be useful for any Ruby developer to have in their toolkit.