Wednesday, January 8, 2025
HomeMathematicsRuby | Enumerable max() function

Ruby | Enumerable max() function

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:

See also  What is cot 2X in terms of the sine and cosine of complementary angles?

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:

See also  Binary Numbers List

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Top 10 Youtubers in India

Who is Tammy Slaton?

Types of Software Testing

Recent Comments

0
Would love your thoughts, please comment.x
()
x