Project

General

Profile

Feature #4553 ยป pick_pop.diff

implementation and tests for Set#pick and Set#pop - adgar (Michael Edgar), 04/05/2011 08:10 AM

View differences:

lib/set.rb (working copy)
223 223
    self
224 224
  end
225 225

  
226
  # Picks an arbitrary element from the set and returns it. Use +pop+ to
227
  # pick and delete simultaneously.
228
  def pick
229
    @hash.first.first
230
  end
231

  
232
  # Picks an arbitrary element from the set and deletes it. Use +pick+ to
233
  # pick without deletion.
234
  def pop
235
    key = pick
236
    @hash.delete(key)
237
    key
238
  end
239

  
226 240
  # Adds the given object to the set and returns self.  Use +merge+ to
227 241
  # add many elements at once.
228 242
  def add(o)
......
1027 1041
    }
1028 1042
  end
1029 1043

  
1044
  def test_pick
1045
    set = Set[5,3,1]
1046
    assert_equal(true, set.include?(set.pick))
1047
  end
1048

  
1049
  def test_pop
1050
    total = Set[9,1,8,2,7]
1051
    
1052
    current = Set[9,1,8,2,7]
1053
    removed = Set[]
1054
    
1055
    until current.empty?
1056
      removed << current.pop
1057
      assert_equal(total, current | removed)
1058
      assert_equal(true, (current & removed).empty?)
1059
    end
1060
  end
1061

  
1030 1062
  def test_add
1031 1063
    set = Set[1,2,3]
1032 1064