Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way to get the value in an array, minimizing a certain class attribute?

Tags:

sorting

ruby

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?

like image 247
user3391564 Avatar asked Mar 07 '14 07:03

user3391564


People also ask

How do you find the max value of an attribute in an array object?

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.

How do you find the minimum value of an array of objects?

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.

Which method on array can be used to remove value from the end?

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.


1 Answers

This will do:

people_array.min_by(&:get_age)
people_array.max_by(&:get_age)
people_array.sort_by(&:get_age)
like image 180
sawa Avatar answered Sep 28 '22 03:09

sawa