How to find max attribute for ruby ​​entries?

I have several records with several attributes (A, B, C, D).

I want to find which record has a higher value for a given attribute, for example D.

How to do it?

+6
source share
2 answers

You can give max_by look.

objects = [some array of objects] object_with_highest_value = objects.max_by {|obj| obj.desired_value } 
+19
source

Depending on the number of records, you may have a more efficient search in the database. I would order the desired attribute in descending order and take the first entry:

 User.order('field DESC').first 
+2
source

Source: https://habr.com/ru/post/899190/


All Articles