This is a vacuous truth. It's the standard interpretation of a universal quantification, i.e. a
collection.all? { |x| some_predicate(x) }
over an empty collection
, but it's known to strike people as counter-intuitive when they first see it in a formal setting. One nice way to think about why this is the preferred semantics is to think about how you would implement all?
.
To make your test require that the array is non-empty, just do
array.any? && array.all? { |x| x == 2 }
Note that array.any?
is fast no matter how large the array, whereas array.all? { |x| x == 2 }
can be slow, depending on how big array
is and how rare 2
is in it. So put the array.any?
first.
Also note, there are degenerate cases where this won't work, for instance if array
is [nil]
or [false]
. If cases like this might come up, replace array.any?
with array.any? { true }
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…