红宝石 |可枚举的 max_by()函数
enumerable的max_by()是 Ruby 中的一个内置方法,它返回一个满足给定块条件的最大元素数组。当没有给出块时,它返回一个枚举器。
Syntax: enu.max_by(n) {|obj| block}
Parameters: The function takes two parameters n and block. N signifies the number of max_by maximum elements and block signifies the condition.
Return Value: It returns a max element or an array containing N max elements.
示例 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