0

I have an array of arrays, like this:

aa = [ [a,d], [a,d1], [a,d], [b,d], [b,d2], [b,d3], [b,d2], [a,d2] ]

I would like to have a unique array of arrays, not just on the first element - which I can do by doing something like aa.uniq(&:first) - but rather remove the inner arrays if BOTH values match. So the result would be:

aa = [ [a,d], [a,d1], [a,d2], [b,d], [b,d2], [b,d3] ]

Can anyone assist in pointing me to an efficient way of doing this? I have large nr of arrays - in the order of 1 million - that I need to process.

Any help appreciated! John

1
  • what do you mean by aa.uniq(&:first)? Commented May 10, 2013 at 9:00

3 Answers 3

2

If you need to maintain a collection of elements where each element is unique and their order is not important. You should use a Set. For instance,

require 'set'
my_set = Set.new
my_set << [1, 'a']
my_set << [1, 'a']
my_set << [1, 'b']
my_set.each { |elem| puts "#{elem}" }

It will give you

[1, "a"]
[1, "b"]

If the order is important, then use the uniq! on you array

aa.uniq!
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to get unique elements from an array, which will remove duplicate element, you can try this:

a = [[1, 2], [2, 3], [1, 2], [2, 3], [3, 4]]
a & a #=> [[1, 2], [2, 3], [3, 4]]

Comments

0

Try like this:

aa = [ ["a","d"], ["a","d1"], ["a","d"], ["b","d"] ]
aa.uniq
aa=[["a", "d"], ["a", "d1"], ["b", "d"]]

You missed double quotations ("). Inside of array, variables a, d, a, d1, etc. are strings. So, you should put them inside of double quotations ("").

Comments

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.