DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

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

09.03.2008
| 4282 views |
  • submit to reddit
        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...)