红宝石 |可数的?函数
枚举的one?()是 Ruby 中的一个内置方法,如果枚举中的一个对象恰好满足给定条件,则返回布尔值 true,否则返回 false。如果给出了一个模式,那么如果任何一个对象与模式完全匹配,它就会返回 true。
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.
示例 #1 :
# Ruby program for one? method in Enumerable
# Initialize an enumerable
enu1 = [10, 19, 18]
# checks if all numbers are greater
# than 4 or not
res1 = enu1.one? { |num| num>4}
# prints the result
puts res1
# checks if all numbers are greater
# than 4 or not
res2 = enu1.one? { |num| num>=19}
# prints the result
puts res2
输出:
false
true
示例 #2 :
# 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
输出:
false
true