andreofthecape
andreofthecape

Reputation: 1196

Recursion with nested array with hashes

I'm not getting this to work correctly.

I have an array of hashes with a nested arrays of hashes of varying depth. If any of the nested results are false it must return false otherwise true.

array = [
  {
    result: true,
    dependents: [
      {
        result: true,
        dependents: [
          {result: true},
          {result: false}
        ]
      }
    ]
  },
  result: true,
  dependents: []
]

def result(array)
   if array.find {|line| line[:result] == false}
    return false
   else
    array.each do |line| 
      result(line[:dependents])
    end
  end
  true    
end

result(array)
#=> true (should be false)

The method result() is not working correctly at the moment as it is returning true for the given array and should be false. Any ideas?

Upvotes: 0

Views: 442

Answers (2)

fbonetti
fbonetti

Reputation: 6672

You're recursively calling the result method but you aren't breaking when the result of that call returns false.

def result(array)
  array.each do |h|
    return false if h[:result] == false
    return false if h[:dependents] && result(h[:dependents]) == false
  end

  true
end

Upvotes: 1

konsolebox
konsolebox

Reputation: 75478

  result(line[:dependents])

Probably must be

  return false if not result(line[:dependents])  ## Or unless ...

Or perhaps simply

  result(line[:dependents]) or return false

Upvotes: 1

Related Questions