Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby on rails how to take lowest/biggest number from array

I have an array with products, I need to display only 1 product, with the largest number in available_amount. How can i do this?

How do I iterate to display products with parameters:

- @part.wh_ps.sort_by(&:available_amount).each do |whp|

product number1: available_amount: 2;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

product number2: available_amount: 5;

>Solution :

If those objects are mapped from the database being the result of a query and you already have them in memory, then you could use Enumerable#max_by:

@part.wh_ps.max_by(&:available_amount)

It should return the object within that array with the biggest available_amount if any.

If you need the one with the lowest available_amount, then Enumerable#min_by, and if you need both Enumerable#minmax_by.

However if that’s not the case and you’re hitting the database again, you could consider making the exact query using SQL (ActiveRecord) asking for the row with the biggest value for the given column.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading