The one?() of enumerable is an inbuilt method in Ruby returns a boolean value true if exactly one of the object in the enumerable satisfies the given condition, else it returns false. If a pattern is given, it returns true if any one object matches with exactly pattern.
Syntax enu.one? { |obj| block } or enu.one?(pattern)
Parameters: The function takes two types of parameters, one is the object and the block, while the other is the pattern.
Return Value: It returns a boolean value.
Example #1:
Ruby
enu1 = [ 10 , 19 , 18 ]
res1 = enu1.one? { |num| num> 4 }
puts res1
res2 = enu1.one? { |num| num>= 19 }
puts res2
|
Output:
false
true
Example #2:
Ruby
enu1 = [ 10 , 19 , 20 ]
res1 = enu1.one?( Numeric )
puts res1
enu2 = [ nil , 1 ]
res2 = enu2.one?
puts res2
|
Output:
false
true