Method: Array#any?
- Defined in:
- array.c
#any? ⇒ Boolean #any?(object) ⇒ Boolean #any? {|element| ... } ⇒ Boolean
Returns whether for any element of self
, a given criterion is satisfied.
With no block and no argument, returns whether any element of self
is truthy:
[nil, false, []].any? # => true # Array object is truthy.
[nil, false, {}].any? # => true # Hash object is truthy.
[nil, false, ''].any? # => true # String object is truthy.
[nil, false].any? # => false # Nil and false are not truthy.
With argument object
given, returns whether object === ele
for any element ele
in self
:
[nil, false, 0].any?(0) # => true
[nil, false, 1].any?(0) # => false
[nil, false, 'food'].any?(/foo/) # => true
[nil, false, 'food'].any?(/bar/) # => false
With a block given, calls the block with each element in self
; returns whether the block returns any truthy value:
[0, 1, 2].any? {|ele| ele < 1 } # => true
[0, 1, 2].any? {|ele| ele < 0 } # => false
With both a block and argument object
given, ignores the block and uses object
as above.
Special case: returns false
if self
is empty (regardless of any given argument or block).
Related: see Methods for Querying.
7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 |
# File 'array.c', line 7783
static VALUE
rb_ary_any_p(int argc, VALUE *argv, VALUE ary)
{
long i, len = RARRAY_LEN(ary);
rb_check_arity(argc, 0, 1);
if (!len) return Qfalse;
if (argc) {
if (rb_block_given_p()) {
rb_warn("given block not used");
}
for (i = 0; i < RARRAY_LEN(ary); ++i) {
if (RTEST(rb_funcall(argv[0], idEqq, 1, RARRAY_AREF(ary, i)))) return Qtrue;
}
}
else if (!rb_block_given_p()) {
for (i = 0; i < len; ++i) {
if (RTEST(RARRAY_AREF(ary, i))) return Qtrue;
}
}
else {
for (i = 0; i < RARRAY_LEN(ary); ++i) {
if (RTEST(rb_yield(RARRAY_AREF(ary, i)))) return Qtrue;
}
}
return Qfalse;
}
|