红宝石 |都可以枚举吗?函数
enumerable的all?()是 Ruby 中的一个内置方法,如果 enumerable 中的所有对象都满足给定条件,则返回布尔值 true,否则返回 false。如果给定一个模式,它会与该模式进行比较,如果它们都等于给定的模式,则返回 true,否则返回 false。
Syntax enu.all? { |obj| block } or enu.all?(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 none of the objects are false or nil.
Return Value: It returns a boolean value.
示例 #1: :
# Ruby program for all? method in Enumerable
# Initialize an enumerable
enu1 = [10, 19, 18]
# checks if all numbers are greater
# than 4 or not
res1 = enu1.all? { |num| num>4}
# prints the result
puts res1
# ch__LINE__ecks if all numbers are greater
# than 4 or not
res2 = enu1.all? { |num| num>=15}
# prints the result
puts res2
输出:
true
false
示例 2 :
# Ruby program for all? method in Enumerable
# Initialize an enumerable
enu1 = [10, 19, 20]
# Checks
res1 = enu1.all?(Numeric)
# prints the result
puts res1
# Initialize
enu2 = [nil, nil]
# Checks
res2 = enu2.all?
# prints the result
puts res2
输出:
true
false