From 8dded0725b1ed215c8da1131a132b4ca6eb2f434 Mon Sep 17 00:00:00 2001 From: knu Date: Fri, 1 May 2009 07:46:23 +0000 Subject: * lib/set.rb (SortedSet#add): Do not let an uncomparable object in. [Bug #118] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@23320 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- lib/set.rb | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/set.rb b/lib/set.rb index 7b8896c335..ec42b93fab 100644 --- a/lib/set.rb +++ b/lib/set.rb @@ -20,7 +20,7 @@ # # The method +to_set+ is added to Enumerable for convenience. # -# See the Set class for an example of usage. +# See the Set and SortedSet documentation for examples of usage. # @@ -451,7 +451,35 @@ class Set end end -# SortedSet implements a set which elements are sorted in order. See Set. +# +# SortedSet implements a Set that guarantees that it's element are +# yielded in sorted order (according to the return values of their +# #<=> methods) when iterating over them. +# +# All elements that are added to a SortedSet must include the +# Comparable module. +# +# Also, all elements must be mutually comparable: el1 <=> +# el2 must not return nil for any elements el1 +# and el2, else an ArgumentError will be raised when +# iterating over the SortedSet. +# +# == Example +# +# require "set" +# +# set = SortedSet.new(2, 1, 5, 6, 4, 5, 3, 3, 3) +# ary = [] +# +# set.each do |obj| +# ary << obj +# end +# +# p ary # => [1, 2, 3, 4, 5, 6] +# +# set2 = SortedSet.new(1, 2, "3") +# set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed +# class SortedSet < Set @@setup = false @@ -476,6 +504,12 @@ class SortedSet < Set @hash = RBTree.new super end + + def add(o) + o.is_a?(Comparable) or raise ArgumentError, "value must be comparable" + super + end + alias << add } rescue LoadError module_eval %{ @@ -495,9 +529,9 @@ class SortedSet < Set end def add(o) + o.is_a?(Comparable) or raise ArgumentError, "value must be comparable" @keys = nil - @hash[o] = true - self + super end alias << add -- cgit v1.2.3