End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#one?
enum.one? [{ |obj| block }] → true or false
enum.one?(pattern) → true or false
enum.c
View on GitHub ↗
static VALUE
enum_one(int argc, VALUE *argv, VALUE obj)
{
struct MEMO *memo = MEMO_ENUM_NEW(Qundef);
VALUE result;
WARN_UNUSED_BLOCK(argc);
rb_block_call(obj, id_each, 0, 0, ENUMFUNC(one), (VALUE)memo);
result = memo->v1;
if (result == Qundef) return Qfalse;
return result;
}
Passes each element of the collection to the given block. The method returns true if the block returns true exactly once. If the block is not given, one? will return true only if exactly one of the collection members is true.
If instead a pattern is supplied, the method returns whether pattern === element for exactly one collection member.
Example
%w{ant bear cat}.one? { |word| word.length == 4 } #=> true %w{ant bear cat}.one? { |word| word.length > 4 } #=> false %w{ant bear cat}.one? { |word| word.length < 4 } #=> false %w{ant bear cat}.one?(/t/) #=> false [ nil, true, 99 ].one? #=> false [ nil, true, false ].one? #=> true [ nil, true, 99 ].one?(Integer) #=> true [].one? #=> false