Jerome
Jerome

Reputation: 6189

Extract minimum from array of records

A statement defines

<% @groups_for_unit = @groups.select{ |i| i.typeunit_id == unit.id } %>

to be able to present the array by typeunit_id

However this array within the greater set of data needs to have a minimum value extracted form it.

<%= @groups_for_unit %>

renders the array, but the following gives an undefined method for quantity for Array Error

<%= @groups_for_unit.quantity.map(&:to_i).min %>

What is the proper syntax to achieve the result?

Upvotes: 0

Views: 58

Answers (1)

Stefan
Stefan

Reputation: 114158

You can use min_by to find the group with the smallest quantity:

min_group = @groups_for_unit.min_by { |x| x.quantity.to_i }

Or map and min to find the smallest quantity:

min_quantity = @groups_for_unit.map { |x| x.quantity.to_i }.min

Upvotes: 2

Related Questions