Do all? and any? guarantee short-circuit evaluation?
ruby
Solution
Yes.
In the final draft of the Ruby standard, `all?` is defined as such:
- Invoke the method `each` on the receiver
- For each element X which the method `each` yeilds:
- If block is given, call block with X as argument. If this call returns a falseish object, return false.
- If block is not given, and X is a falseish object, return false.
- Return true.
Note the word return in step 2. This guarantees short circuit evaluation. `any?` is defined similarly. However the standard is still a draft and I don't know which Ruby implementations (if any) aim to be standards-compliant.
Problem
Testing out some code in both `pry` and `irb`, I get the following results: ``` [1] pry(main)> a = [1, 3, 5, 7, 0] => [1, 3, 5, 7, 0] [2] pry(main)> a.any? {|obj| p obj; 3 / obj > 1} 1 => true [3] pry(main)> a.all? {|obj| p obj; 3 / obj > 1} 1 3 => false ``` In `[2]` and `[3]` I see that there appears to be short-circuit evaluation that aborts the iteration as soon as possible, but is this guaranteed behaviour? Reading the documentation there is no mention of this behaviour. I realise that I can use `inject` instead as that will iterate over everything, but I'm interested in finding out what the official Ruby view is.