views:

532

answers:

3
+4  Q: 

Sets in Ruby?

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.

+3  A: 

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

thr
+1  A: 

From the documentation:

a = [ "a", "a", "b", "b", "c" ]
a.uniq  #gets you ["a", "b", "c"]
a.uniq.uniq! #gets you nil (no duplicates :)
dirkgently
Is there something similar that tells me that there are duplicates in the array? Or does uniq have any return value?
alamodey
uniq: Returns a new array by removing duplicate values in self. uniq!: Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
dirkgently
+9  A: 

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
ucron