红宝石 |可以枚举吗?函数
可枚举的any?()是 Ruby 中的内置方法,如果可枚举中的任何对象满足给定条件,则返回布尔值,否则返回 false。
Syntax enu.any? { |obj| block } or enu.any?(pattern)
Parameters: The function takes two types of parameters, one is the object and the block, while the other is the pattern. In case nothing is passed, it assumes to be default object and block which returns true if any of the objects are false or nil.
Return Value: It returns a boolean value.
示例 1 :
# Ruby program for any? method in Enumerable
# Initialize an enumerable
enu1 = [10, 19, 18]
# checks if any numbers are greater
# than 13 or not
res1 = enu1.any? { |num| num>13}
# prints the result
puts res1
res2 = enu1.any? { |num| num>=20}
# prints the result
puts res2
输出:
true
false
示例 2 :
# Ruby program for any? method in Enumerable
# Initialize an enumerable
enu1 = [10, 19, 20]
# Checks
res1 = enu1.any?(Numeric)
# prints the result
puts res1
# Initialize
enu2 = [nil, 10]
# Checks
res2 = enu2.any?
# prints the result
puts res2
输出:
true
true