0

I'm having a problem trying to get objects from an array where a given hash might either have a specific property and a specific value, or a nested hash which potentially can too.

Is there a method for returning the specific hash that has the key I need OR RECURSE when it doesn't?

Example: I have this completely made-up structure:

  the_array = [
  {
    :is_father => true, 
    :seek_this => "01"  
  },
  {
    :is_uncle => false,
    :children => [
       {
         :seek_this => "09"
       },
       {
         :seek_this => "2a"
       }
    ]
  },
  {
    :random_property=> 3,
    :children => {
      :random_er => true,
      :children => [
        {
          :is_father => false,
          :children => [
             {
               :seek_this => "3b"
             },
             {
               :seek_this => "h1"
             }
          ]
        }
      ]
    }
  }
]

And after calling

the_array
  .methodThatIDoNotKnow { |x| !x.seek_this.nil? } 
  .each do |hash_i_need|
  //operate on hash somehow
  hash_i_need.seek_this = 0xDEADBEEF
end

This is what I would expect to have happened:

  the_array = [
  {
    :some_key => true, 
    :seek_this => 0xDEADBEEF
  },
  {
    :some_other_key => false,
    :children => [
       {
         :seek_this => 0xDEADBEEF
       },
       {
         :seek_this => 0xDEADBEEF
       }
    ]
  },
  {
    :random_key: 3,
    :children => {
      :random_er => true,
      :children  => [
        {
          :is_father => false,
          :children  => [
             {
               :seek_this => 0xDEADBEEF
             },
             {
               :seek_this => 0xDEADBEEF
             }
          ]
        }
      ]
    }
  }
]

I understand this is something that I can code myself, I'm just wondering if I need to or there is functionality for this kind of search out of the box.

Thanks!

Carlos Vergara
  • 657
  • 6
  • 19

1 Answers1

0

there is a fetch method on hash but it doesn't recurse through object

you could use this answer or there are many deep fetch examples out there. good luck!

Community
  • 1
  • 1
engineerDave
  • 3,887
  • 26
  • 28