alamodey
alamodey

Reputation: 14938

Are there 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.

Upvotes: 36

Views: 31541

Answers (2)

ucron
ucron

Reputation: 2852

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

Upvotes: 76

dirkgently
dirkgently

Reputation: 111150

From the documentation:

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

Upvotes: 22

Related Questions