Open In App

How to Access elements of nested hashes in Ruby?

RIn this article, we will discuss how to access elements of nested hashes in Ruby. We can access elements of nested hashes through different methods ranging from using the dig method to the fetch method.

Access elements of nested hashes using square brackets

In this method, square brackets are used with keys to access nested hash elements.

Syntax:

nested_hash[key1][key2]...

Example: In this example, we use square brackets with keys to access nested hash elements

# Example nested hash
nested_hash = {
  key1: {
    key2: {
      key3: "geeksforgeeks "
    }
  }
}

# Access elements of nested hashes using square brackets
 
value1 = nested_hash[:key1][:key2][:key3]
puts "Value: #{value1}"

Output
Value: geeksforgeeks 

Access elements of nested hashes using dig method

The dig method in Ruby's Hash class allows us to access nested hash elements using a sequence of keys as arguments

Syntax:

nested_hash.dig(key1, key2, ...)

Example: In this example, we use dig method to access the value by passing the keys as arguments

# Example nested hash
nested_hash = {
  key1: {
    key2: {
      key3: "geekforgeeks"
    }
  }
}

# Access elements of nested hashes using dig method
value2 = nested_hash.dig(:key1, :key2, :key3)
puts "Value: #{value2}"
 

Output
Value: geekforgeeks

Access elements of nested hashes using fetch method

The fetch method allows us to access nested hash elements.

Syntax:

nested_hash.fetch(key1).fetch(key2)...

Example: In this example we use fetch method to access the nested hash elements

# Example nested hash
nested_hash = {
  key1: {
    key2: {
      key3: "geekforgeeks"
    }
  }
}

 

#  Access elements of nested hashes using fetch method
value3 = nested_hash.fetch(:key1).fetch(:key2).fetch(:key3)
puts "Value: #{value3}"
 

Output
Value: geekforgeeks
Article Tags :