Jeff
Jeff

Reputation: 4003

use ruby to identify if array of terms contains one and ONLY one repeated term

In categorical logic, categorical syllogism requires four terms, but can only have three unique terms; that is one and ONLY one term can and must be repeated.

I trying to write a Ruby test for this but having a little bit of trouble.

Consider the following three arrays of terms, the first of which is a valid list, while the other two are invalid (termarray2 contains 4 unique terms and termarray3 contains only 2 unique terms).

termarray1 = ["Dogs", "Mortal Things", "Mortal Things", "Living Things"]
termarray2 = ["Dogs", "Mortal Things", "Cats", "Living Things"] 
termarray3 = ["Dogs", "Mortal Things", "Mortal Things", "Dogs"]

I want to write a test called three_terms?

It should return true for termarray1 and false for termarray2 and termarray3

Any ideas how I could to this?

Upvotes: 0

Views: 57

Answers (2)

SHS
SHS

Reputation: 7744

The uniq methods returns the unique elements in an array.

This should work:

array.uniq.count == 3

But the test you mention also checks that the original array has four elements. Thus the entire check should be:

(array.count == 4) && (array.uniq.count == 3)

Upvotes: 4

August
August

Reputation: 12558

Check to see if the size of unique elements is 3 (using Array#uniq):

array.uniq.size == 3

You could also monkey-patch Array with three_terms?:

class Array
  def three_terms?
    uniq.size == 3
  end
end

Upvotes: 2

Related Questions