📜  红宝石 |可枚举的 max_by()函数

📅  最后修改于: 2022-05-13 01:54:39.966000             🧑  作者: Mango

红宝石 |可枚举的 max_by()函数

enumerablemax_by()是 Ruby 中的一个内置方法,它返回一个满足给定块条件的最大元素数组。当没有给出块时,它返回一个枚举器。

示例 1

Ruby
# Ruby program for max_by method in Enumerable
 
# Initialize
a = ["gopal", "tunday", "geeks", "classes", "linux"]
 
# Prints
p a.max_by(2) {|obj| obj.length }
 
p a.max_by {|obj| obj.length }


Ruby
# Ruby program for max_by method in Enumerable
 
# Initialize
a = ["gopal", "tunday", "geeks", "classes", "linux"]
 
# Prints
p a.max_by(2)
 
p a.max_by


输出

["classes", "tunday"]
"classes"

示例 2

红宝石

# Ruby program for max_by method in Enumerable
 
# Initialize
a = ["gopal", "tunday", "geeks", "classes", "linux"]
 
# Prints
p a.max_by(2)
 
p a.max_by

输出

Enumerator: ["gopal", "tunday", "geeks", "classes", "linux"]:max_by(2)
Enumerator: ["gopal", "tunday", "geeks", "classes", "linux"]:max_by