Question

I need a collection that is like a set. Basically I'm scanning a long string and adding words to the collection but I want to be able to detect when there are duplicates.

If sets aren't available, what's the most efficient way of doing this in Ruby? Brownie points for example code.

Was it helpful?

Solution

From the documentation:

a = [ "a", "a", "b", "b", "c" ]
a.uniq  #gets you   ["a", "b", "c"]
a.uniq.uniq! #gets you nil (no duplicates :)

OTHER TIPS

There is a Set class in ruby. You can use it like so:

require 'set'

set = Set.new

string = "a very very long string"

string.scan(/\w+/).each do |word|
  unless set.add?( word )
    # logic here for the duplicates
  end
end

Although, I'm wondering if you would want to count the instances in that case the following example would be better:

instances = Hash.new { |h, k| h[k] = 0 }

string.scan(/\w+/).each do |word|
  instances[word] += 1
end

Check out this url /core/classes/Set.html over at ruby-doc.org

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top