Sets in Ruby? Sets in Ruby? ruby ruby

Sets in Ruby?


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

require 'set'set = Set.newstring = "a very very long string"string.scan(/\w+/).each do |word|  unless set.add?( word )    # logic here for the duplicates  endend

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] += 1end


From the documentation:

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