红宝石 |可枚举的 min_by()函数
enumerable的min_by()是 Ruby 中的一个内置方法,它返回一个满足给定块条件的最小元素数组。当没有给出块时,它返回一个枚举器。
Syntax: enu.min_by(n) { |obj| block }
Parameters: The function takes two parameters n and block. N signifies the number of minimum elements and block signifies the condition.
Return Value: It returns a min element or an array containing N min elements.
示例 #1 :
# Ruby program for min_by method in Enumerable
# Initialize
a = ["gopal", "tunday", "geeks", "classes", "linux"]
# Prints
p a.min_by(2) {|obj| obj.length }
p a.min_by {|obj| obj.length }
输出:
["geeks", "gopal"]
"gopal"
示例 #2 :
# Ruby program for min_by method in Enumerable
# Initialize
a = ["gopal", "tunday", "geeks", "classes", "linux"]
# Prints
p a.min_by(2)
p a.min_by
输出:
Enumerator: ["gopal", "tunday", "geeks", "classes", "linux"]:min_by(2)
Enumerator: ["gopal", "tunday", "geeks", "classes", "linux"]:min_by