Over a million developers have joined DZone.

Reaching A Hash Within An Array Of (arrays Of) Hashes

·
If you have an array of (arrays of) hashes and you want to reach to a particular hash in it, here's a simple method to do it by overloading the Array class with a recursive iterator.
Of course, if the structure is part of one of your classes, you can just as well add it there.


class Array
  def node_change
    hunter = Proc.new do |nodes|
      (nodes.map { |n| n.merge(yield(n)) if n.is_a?(Hash) } +
       nodes.map { |n| hunter.call(n)    if n.is_a?(Array) }).compact
    end
    hunter.call self
  end
end


For example, if you have a structure like this:


struct = [ 
          [ 
              { :name => 'alxx' }, 
              { :name => 'joe'} 
          ], 
          [], 
          [ 
            [ 
              { :name => 'john', :height => '127' }
            ]
          ]
        ]

# you can easily add to one of the hashes inside it:

require 'pp'

pp struct.node_change { |node| node[:name] == 'alxx' ? { :height => '172' } : {} }

# or change one:

pp struct.node_change { |node| node[:name] == 'john' ? { :height => '180' } : {} }

# or change all:

pp struct.node_change { |node| { :gender => 'male' } }


This will work regardless of how deep your hash lies (you can have arrays in arrays in arrays, etc...)

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}