Say I have the following class:
class Person
def initialize(name, age)
@name = name
@age = age
end
def get_age
return @age
end
end
And I have an array of Person
objects. Is there a concise, Ruby-like way to get the person with the minimum (or maximum) age? What about sorting them by it?
Maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method is by using the Math. max. apply() method.
Using map(), Math, and the spread operator map() function, we take all of our Y values and insert them into a new Array of Numbers. Now that we have a simple Array of numbers, we use Math. min() or Math. max() to return the min/max values from our new Y value array.
pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array.
This will do:
people_array.min_by(&:get_age)
people_array.max_by(&:get_age)
people_array.sort_by(&:get_age)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With