patternrubyrailsMinor
Find out if attributes are identical
Viewed 0 times
areidenticalattributesfindout
Problem
I have an array of active record objects. All objects have an attribute
My goal is to find out if all result attributes are identical. If not then I will have to return mixed but if they are then I return the value of the attributes.
I currently have this code:
But that first line is quite ugly. I'm sure there is a better way to find out if all results are identical or not but I can't think of any.
result and the value of result can be either 'failed' or 'passed'.My goal is to find out if all result attributes are identical. If not then I will have to return mixed but if they are then I return the value of the attributes.
I currently have this code:
if tests.map(&:result).uniq.count != 1
'mixed'
else
tests.first.result
endBut that first line is quite ugly. I'm sure there is a better way to find out if all results are identical or not but I can't think of any.
Solution
You could try the appropriately named
Edit: As tokland points out, you'll want to check if
But you could also do the check in the database layer with something like:
Obviously you'll want to scope the query more specifically.
Also note that here, an empty collection returns a
#all? method:reference = tests.first.result
if tests.all? { |test| test.result == reference }
reference
else
'mixed'
endEdit: As tokland points out, you'll want to check if
tests is empty before any of this. Otherwise, tests.first will of course be nil.But you could also do the check in the database layer with something like:
if Test.select(:result).distinct.count > 1
'mixed'
else
Test.first.try(:result)
endObviously you'll want to scope the query more specifically.
Also note that here, an empty collection returns a
nil (because if Test.first is nil, then .try(:result) will also be nil).Code Snippets
reference = tests.first.result
if tests.all? { |test| test.result == reference }
reference
else
'mixed'
endif Test.select(:result).distinct.count > 1
'mixed'
else
Test.first.try(:result)
endContext
StackExchange Code Review Q#136260, answer score: 2
Revisions (0)
No revisions yet.