0

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?

1
  • 1
    It helps people answering you if you break-down complex data into something that fits into the default code display width. The more readable your question is, the easier it is for others to understand, and the faster they can help you. Commented Jul 14, 2014 at 18:10

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

You might consider showing your code returns the correct values for one array where it should return true and another for where it should return false. I prefer key? to checking if a hash value is nil, as nil values are permitted.
Thanks, works and I found I could extend your solution easier.
1
  result(line[:dependents])

Probably must be

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

Or perhaps simply

  result(line[:dependents]) or return false

1 Comment

Thanks, this works, just found @fbonetti answer easier to extend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.