Issue #12110 has been updated by Martin Drst.


Andrew Vit wrote:

> This is still surprising to me, it looks like a contradiction:
> 
> ```
> [].any? #=> false
> [].all? #=> true
> ```
> 
> I would expect "all" to be a superset of "any": both should mean "at least one".
> Is there a reason for the existing behavior, or is it just history now?

It's the way it works in Mathematics. But I'll try to explain it without using too much Mathematical terminology.

all? doesn't ask "at least one"?, but really "are all of those that are in the array true?". If there's no element in the array, then the condition is indeed true for all elements in the array.

Another way to try to understand this is to look at how these operations can be expressed by using reduce:

def any? (&block)
  reduce(q1) { |memo, e| memo or block.call(e) }
end

def all? (&block)
  reduce(q2) { |memo, e| memo and block.call(e) }
end

So both of these operations are map-reduce operations. The mapping is done with the block, converting array elements to true/false booleans. The reduction is 'or' for any? and 'and' for all?. Now the question for you is to figure out what we should put instead of q1 and q2. Hint: First make sure you get q1 and q2 right for arrays with actual elements. Then see what you get from the above definitions with empty arrays.

[In Mathematical terms, false is the neutral element of logical OR, and true is the neutral element of logical AND, the same way 0 is the neutral element of addition, and 1 is the neutral element of multiplication. Therefore, the sum of zero elements is 0, but the product of zero elements is 1.]

----------------------------------------
Feature #12110: Create a method to avoid vacuous truth?
https://bugs.ruby-lang.org/issues/12110#change-57178

* Author: Waldyr de Souza
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
I often find myself running into unexpected results when using #all? for example

[].all? { |e| false } # => true

Even though it's logically correct could we have a method that express the following?

foo.any? && foo.all?(&:bar)



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>