In Ruby, the max() function is part of the *Enumerable* module, which provides a set of methods for working with collections like arrays, ranges, and hashes. The max() function returns the largest element in the collection. By default, it compares elements using their natural order.
For example, calling max() on an array of numbers:
ruby
numbers = [3, 5, 1, 7, 2]
puts numbers.max # Output: 7
If the collection contains objects or requires custom comparison, you can provide a block to the max() function. This block determines how the elements are compared. For example, to find the longest string in an array:
ruby
words = [“apple”, “banana”, “cherry”]
puts words.max { |a, b| a.length <=> b.length } # Output: “banana”
The max() function can also accept an argument to limit the number of largest elements returned, such as max(2) to return the top two elements.