0

I am creating a simple method that compares numbers in an array. There are rules, but I don't think that information is needed.

def nearest_larger(arr, idx)
  diff = 1
  p arr.length
  while true
    left = idx - diff
    right = idx + diff
    if (left >= 0) && (arr[left] > arr[idx])
      return left
    elsif (arr[right] > arr[idx]) && (right < arr.length)
      return right
    elsif (left < 0) && (right >= arr.length)
      return nil
    end

    diff += 1
  end
end
puts(nearest_larger([2,1,1,1], 0))

so when i change (arr[right] > arr[idx]) && (right < arr.length) to (right < arr.length) && (arr[right] > arr[idx]) everything works fine.

why does the order matter here?

2 Answers 2

2

The order matters, because in a && conditional statement, Ruby evaluates the left side first. If the left side evaluates to false, it doesn't even bother to check the right side, because it already knows that the entire condition is false.

So, for (arr[right] > arr[idx]) && (right < arr.length), it first evaluates:

(arr[right] > arr[idx])

This throws an error, because you're encountering a nil value, and there is no > method for nil.

But, for (right < arr.length) && (arr[right] > arr[idx]), it first evaluates:

(right < arr.length)

As soon as that returns false, it stops and calls the entire condition false, and doesn't ever evaluate the 2nd part; so there is no error.

Sign up to request clarification or add additional context in comments.

1 Comment

its funny how easy an explanation makes things. for some reason i guess i thought it would evaluate both before making a decision .... thanks for the help!
1

Because this is a short-circuited condition.

(arr[right] > arr[idx])

still evaluates to undefined method for nil class, however it is not evaluated because the first part of the condition fails.

Comments

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.