siekfried
siekfried

Reputation: 2964

Find if a collection of objects have the same value for a given attribute

I have two related models : Invoice and Currency.

Invoice belongs_to Currency and Currency has_many Invoices

I have a table which displays the list of every invoices and I am able to filter them by currency. An invoice also has a pricefield and I have a method which calculates the total price of invoices I display.

My problem is that I want to display the total price if and only if every invoices have the same currency.

I am pretty sure there is a simple way to achieve this but I can't find it out.

Any help would be greatly appreciated.

Upvotes: 2

Views: 3572

Answers (2)

dbenhur
dbenhur

Reputation: 20408

The most straight forward way to ask if everything in a collection is the same is to ask if all elements equal the first one:

invoices.all?{ |inv| inv.currency_id == invoices.first.currency_id }

If you do this thing a lot, one might consider extended Enumerable with a convenience method:

module Enumerable
  def all_same?
    v = first
    all? {|e| e == v}
  end
end

invoices.map(&:currency_id).all_same?

Upvotes: 2

roman-roman
roman-roman

Reputation: 2796

in fact, there are many ways to achieve that, e.g, you can check if all of them have the same currency this way:

invoices.reject {|inv| inv.currency_id == invoices[0].currency_id}.empty?

or

invoices.map {|inv| inv.currency_id}.uniq.length == 1

Upvotes: 4

Related Questions