2

I have a "Q&A" array and each element is a subarray of three elements (Q, A and Animal). How can I select all the unique animals?

I can select the animals alone with:

[@q_and_a[0][2]] + [@q_and_a[1][2]] + [@q_and_a[2][2]] +[@q_and_a[3][2]] 
# => ["Elephant", "Elephant", "Spider", "Spider"]
2
  • 3
    Please provide sample input and output. Commented Jul 5, 2013 at 17:24
  • If you are using rails (activerecord) you have the #pluck method: animals = QnAModel.pluck(:animal).uniq. I know it's not what you are looking for, but many might be. Se also: stackoverflow.com/a/9872725/741850 Commented Jul 5, 2013 at 20:21

3 Answers 3

5

Use the map and uniq function

@q_and_a.map { |a| a[2] }.uniq
Sign up to request clarification or add additional context in comments.

Comments

-1

if your variable is called myElems then you can use the following:

myElems = [@q_and_a[0][2]] + [@q_and_a[1][2]] + [@q_and_a[2][2]] +[@q_and_a[3][2]]
myElems.uniq
# => ["Elephant","Spider"]

Here is a link with the info on it

Comments

-2
@q_and_a.map{|a| a[2]}.group_by{|e| e}.select{|_, v| v.length == 1}.keys

4 Comments

I guess that depends on how you read the question, I see both as valid possibilities. Given the OP's example output ( No "unique" animals ) I lean towards my interpretation.
@jondavidjohn You are right. what it says as the question does not match with the examples. I took what the question says, and you took what the example suggests.
@jondavidjohn You mention the OPs example output, but notice that that is not what the OP wants to do.
right, he's just showing us his data set... no unique animals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.