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"]
sawa
  • 165,429
  • 45
  • 277
  • 381
junky
  • 1,480
  • 1
  • 17
  • 32
  • 3
    Please provide sample input and output. – Andrew Marshall Jul 05 '13 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: http://stackoverflow.com/a/9872725/741850 – Automatico Jul 05 '13 at 20:21

3 Answers3

5

Use the map and uniq function

@q_and_a.map { |a| a[2] }.uniq
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158
-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

konkked
  • 3,161
  • 14
  • 19
-2
@q_and_a.map{|a| a[2]}.group_by{|e| e}.select{|_, v| v.length == 1}.keys
sawa
  • 165,429
  • 45
  • 277
  • 381
  • 2
    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 Jul 05 '13 at 17:41
  • @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. – sawa Jul 05 '13 at 17:50
  • @jondavidjohn You mention the OPs example output, but notice that that is not what the OP wants to do. – sawa Jul 06 '13 at 15:06
  • right, he's just showing us his data set... no unique animals. – jondavidjohn Jul 07 '13 at 03:54