Open In App

Ruby | Enumerable one? function

Last Updated : 23 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Ruby program for one? method in Enumerable
   
# Initialize an enumerable
enu1 = [10, 19, 18]  
   
# checks if exactly one number is greater than 4
res1 = enu1.one? { |num| num>4}
 
# prints the result
puts res1
 
 
# checks if exactly one number is greater than or equal to 19
res2 = enu1.one? { |num| num>=19}
 
# prints the result
puts res2


Output:

false
true

Example #2

Ruby




# Ruby program for one? method in Enumerable
   
# Initialize an enumerable
enu1 = [10, 19, 20]  
   
# Checks
res1 = enu1.one?(Numeric)
 
# prints the result
puts res1
 
# Initialize
enu2 = [nil, 1]
 
# Checks
res2 = enu2.one?
# prints the result
puts res2


Output:

false
true


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads