0

So maybe I have this all wrong, but I'm sure there is a way to do this, say I have a an if statement, that I want to return true if all the conditions in an array evaluate as true.

say I have this:

def real_visitor?(location, request, params)

  valid_location = [
    params['referrer'] == 'us',
    params['bot'] != 'googlebot',
    5 + 5 == 10 
  ]

  if valid_location
    return true
  else
    return false
  end
end

How would I evaluate each of the conditions in the array valid_location, some of those conditions in that array are just pseudocode.

1 Answer 1

4

Use Array#any? or Array#all?. It's like putting the || or && operator between all your conditions, but it doesn't do short-circuit evaluation, which is sometimes useful.

return valid_location.all?

You don't need the return keyword, by the way. I'd leave it out.

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

3 Comments

In MRI 1.8.7, all? and any? short-circuit: all? stops at the first falsy value; any? stops at the first truthy value.
Well an example of what I mean is that [puts("1"), puts("2")].all? would print both "1" and "2", but puts("1") && puts("2") would only print "1", even though the semantics are the same. The items in the array are being evaluated before all? is being called.
That makes perfect sense. Thanks for the great explanation.

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.