| 14 |
14 |
# == Overview
|
| 15 |
15 |
#
|
| 16 |
16 |
# This library provides the Set class, which deals with a collection
|
| 17 |
|
# of unordered values with no duplicates. It is a hybrid of Array's
|
|
17 |
# of unordered values with no duplicates. It is a hybrid of Array's
|
| 18 |
18 |
# intuitive inter-operation facilities and Hash's fast lookup. If you
|
| 19 |
19 |
# need to keep values ordered, use the SortedSet class.
|
| 20 |
20 |
#
|
| 21 |
21 |
# The method +to_set+ is added to Enumerable for convenience.
|
| 22 |
22 |
#
|
| 23 |
|
# See the Set class for an example of usage.
|
|
23 |
# See the Set and SortedSet documentation for examples of usage.
|
| 24 |
24 |
|
| 25 |
25 |
|
| 26 |
26 |
#
|
| ... | ... | |
| 434 |
434 |
end
|
| 435 |
435 |
end
|
| 436 |
436 |
|
| 437 |
|
# SortedSet implements a set which elements are sorted in order. See Set.
|
|
437 |
#
|
|
438 |
# SortedSet implements a Set that guarantees that it's element are
|
|
439 |
# yielded in sorted order (according to the return values of their #<=> methods)
|
|
440 |
# when iterating over them.
|
|
441 |
#
|
|
442 |
# All elements that are added to a SortedSet must include the Comparable module.
|
|
443 |
#
|
|
444 |
# Also, all elements must be <em>mutually comparable</em>:
|
|
445 |
# <tt>el1 <=> el2</tt> must not return <tt>nil</tt> for any elements
|
|
446 |
# <tt>el1</tt> and <tt>el2</tt>, else an ArgumentError will be raised
|
|
447 |
# when iterating over the SortedSet.
|
|
448 |
#
|
|
449 |
# == Example
|
|
450 |
#
|
|
451 |
# require "set"
|
|
452 |
#
|
|
453 |
# set = SortedSet.new(2, 1, 5, 6, 4, 5, 3, 3, 3)
|
|
454 |
# ary = []
|
|
455 |
#
|
|
456 |
# set.each do |obj|
|
|
457 |
# ary << obj
|
|
458 |
# end
|
|
459 |
#
|
|
460 |
# p ary # => [1, 2, 3, 4, 5, 6]
|
|
461 |
#
|
|
462 |
# set2 = SortedSet.new(1, 2, "3")
|
|
463 |
# set2.each { |obj| } # => raises ArgumentError: comparison of Fixnum with String failed
|
|
464 |
#
|
| 438 |
465 |
class SortedSet < Set
|
| 439 |
466 |
@@setup = false
|
| 440 |
467 |
|
| ... | ... | |
| 459 |
486 |
@hash = RBTree.new
|
| 460 |
487 |
super
|
| 461 |
488 |
end
|
|
489 |
|
|
490 |
def add(obj)
|
|
491 |
obj.is_a?(Comparable) or raise ArgumentError, "value must be comparable"
|
|
492 |
super
|
|
493 |
end
|
|
494 |
alias << add
|
| 462 |
495 |
}
|
| 463 |
496 |
rescue LoadError
|
| 464 |
497 |
module_eval %{
|
| ... | ... | |
| 477 |
510 |
super
|
| 478 |
511 |
end
|
| 479 |
512 |
|
| 480 |
|
def add(o)
|
|
513 |
def add(obj)
|
|
514 |
obj.is_a?(Comparable) or raise ArgumentError, "value must be comparable"
|
| 481 |
515 |
@keys = nil
|
| 482 |
|
@hash[o] = true
|
| 483 |
|
self
|
|
516 |
super
|
| 484 |
517 |
end
|
| 485 |
518 |
alias << add
|
| 486 |
519 |
|