Revibalog

home

A look into Ruby's Set

07 Oct 2013

Ruby's Set represents an unordered collection of distinct objects, very much like mathematical sets. Each object in the set is assigned as a key in an internal hash table to guarantee uniqueness. The hash values are not of concern to the set, and are always true.

require 'set'
set = Set.new([1,1,2,3,42]) #=> #<Set: {1, 2, 3, 42}>
set.add(1) #=> #<Set: {1, 2, 3, 42}>
set.delete(2) #=> #<Set: {1, 3, 42}>
set.instance_variables #=> [:@hash]
h = set.instance_eval{ @hash } #=> {1=>true, 3=>true, 42=>true}
h.class #=> Hash
h[:a] = ':)' #=> ":)"
h #=> {1=>true, 3=>true, 42=>true, :a=>":)"}
set #=> #<Set: {1, 3, 42, :a}>


comments powered by Disqus