From: Yuri Leikind Date: 2001-11-14T03:10:04+09:00 Subject: [ruby-talk:25050] Re: Set class in Ruby Jason Voegele wrote: > > >> However, sometimes it's convenient to have Sets, collections where > >> there's only ever one of each element. These have different semantics > >> to arrays: they are not necessarily ordered, attempting to add an > >> element doesn't necessarily increase the size, and so on. > > > > So, why doesn't Ruby have Set as a built-in class? > > Paul Brannan and I are working on implementing a library of data structures > and algorithms for Ruby to fill this gap. It is not yet available, but I > have a Set class that you can get at: > > http://www.jvoegele.com/ruby/Set.rb > > Paul also has a similar one that may suit your needs. Yes, cool, this one's pretty similar to what I have. I'd just add a couple of methods: An inspect method, something like that: def inspect '< ' + @store.keys.collect{|e| e.inspect }.join(' ') + ' >' end A dup method, to avoid this: irb(main):003:0> a = Set.new([1 , 2 , 3]) #true, 2=>true, 3=>true}> irb(main):005:0> b=a.dup #true, 2=>true, 3=>true}> irb(main):006:0> b.add 'one more' true irb(main):007:0> p a, b #true, 2=>true, "one more"=>true, 3=>true}> #true, 2=>true, "one more"=>true, 3=>true}> Here @store is not dupped which leads to 2 references to one object instead of two objects A dup method could look like this def dup Set.new(@store.keys) end Also, to be able to use sets as hash keys, #hash method should be defined. #hash should return the same value for all equal sets. My colleague wrote it like this: def hash key = size @store.each_key { |k| key ^= k.hash } return key end > > It is my hope that we'll be able to deliver something that becomes a > standard part of the Ruby programmer's toolset. Well, that's the reason for my writing this letter - suggestion that we have Set class, like yours, built in the language. So I am interested in other people's opinions on the topic - should there be a built-in Set class, and if no, why? -- Best regards, Yuri Leikind