Index: lib/set.rb
===================================================================
--- lib/set.rb (revision 31238)
+++ lib/set.rb (working copy)
@@ -223,6 +223,20 @@
self
end
+ # Picks an arbitrary element from the set and returns it. Use +pop+ to
+ # pick and delete simultaneously.
+ def pick
+ @hash.first.first
+ end
+
+ # Picks an arbitrary element from the set and deletes it. Use +pick+ to
+ # pick without deletion.
+ def pop
+ key = pick
+ @hash.delete(key)
+ key
+ end
+
# Adds the given object to the set and returns self. Use +merge+ to
# add many elements at once.
def add(o)
@@ -1027,6 +1041,24 @@
}
end
+ def test_pick
+ set = Set[5,3,1]
+ assert_equal(true, set.include?(set.pick))
+ end
+
+ def test_pop
+ total = Set[9,1,8,2,7]
+
+ current = Set[9,1,8,2,7]
+ removed = Set[]
+
+ until current.empty?
+ removed << current.pop
+ assert_equal(total, current | removed)
+ assert_equal(true, (current & removed).empty?)
+ end
+ end
+
def test_add
set = Set[1,2,3]