Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing elements of nested hashes in ruby [duplicate]

I'm working a little utility written in ruby that makes extensive use of nested hashes. Currently, I'm checking access to nested hash elements as follows:

structure = { :a => { :b => 'foo' }}  # I want structure[:a][:b]  value = nil  if structure.has_key?(:a) && structure[:a].has_key?(:b) then   value = structure[:a][:b] end 

Is there a better way to do this? I'd like to be able to say:

value = structure[:a][:b] 

And get nil if :a is not a key in structure, etc.

like image 280
Paul Morie Avatar asked Apr 04 '11 22:04

Paul Morie


People also ask

Are nested hashes possible in Ruby?

The hashes that you've seen so far have single key/value pairs. However, just like arrays, they can be nested, or multidimensional.

How do you access hashes in Ruby?

In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.

How do you know if two hashes are equal Ruby?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared.

How do I iterate a Hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.


1 Answers

Traditionally, you really had to do something like this:

structure[:a] && structure[:a][:b] 

However, Ruby 2.3 added a method Hash#dig that makes this way more graceful:

structure.dig :a, :b # nil if it misses anywhere along the way 

There is a gem called ruby_dig that will back-patch this for you.

like image 134
DigitalRoss Avatar answered Sep 20 '22 20:09

DigitalRoss