Search code examples
ruby-on-railsrubyiteratorblock

Look at a hash, find the first key where value is nil, do something with that key/value pair


I'm writing this complex loop structure and would love to make filling my hash a little easier.

At the beginning of my method, I make something that looks like this:

thing_array = [{
animals: nil,
fruit: nil,
cars: nil
},
{
animals: nil,
fruit: nil,
cars: nil
},
{
animals: nil,
fruit: nil,
cars: nil
}]

My goal is to loop through the array, and then each hash, find the first element that's nil and set that key/value pair based on the value of the loop that runs outside of this.

Any suggestions on how to do this?


Solution

  • Like Tin Man said you'll need to make your question clearer. The method below gets you to the first nil value in the array. I wasn't sure what you wanted to do once you got to that point, but hopefully this helps!

    def getFirstNil(array)
       array.each do |hash|
          hash.each do |key,value|
             if value == nil
                #here's your first nil, do something!
                return key
             end
          end
       end
       return nil
    end