Yields a value to the block. The value is unique for each invocation with the same block. Alternatively, you may provide an explicit key to identify the block.
If a block with no parameter is supplied, unique keeps track of previous invocations, and will continue yielding until a unique value is generated. If a unique value is not generated after @UniqueWorker::MAX_TRIES@, an exception is raised.
ParseTree is required unless an explicit key is provided
(1..3).collect { unique {|x| x }} # => [0, 1, 2] (1..3).collect { unique {|x| x + 1 }} # => [1, 2, 3] (1..3).collect { unique {|x| x }} # => [3, 4, 5] # Continued on from above (1..3).collect { unique(:a) {|x| x }} # => [0, 1, 2] # Explicit key overrides block identity a = [1, 1, 1, 2, 2, 3] (1..3).collect { unique { a.shift }} # => [1, 2, 3] (1..3).collect { unique { 1 }} # raises TooManyTriesException
return
# File lib/dm-sweatshop/unique.rb, line 27 27: def unique(key = nil, &block) 28: if block.arity < 1 29: UniqueWorker.unique_map ||= {} 30: 31: key ||= UniqueWorker.key_for(&block) 32: set = UniqueWorker.unique_map[key] || Set.new 33: result = block[] 34: tries = 0 35: while set.include?(result) 36: result = block[] 37: tries += 1 38: 39: raise TooManyTriesException.new("Could not generate unique value after #{tries} attempts") if tries >= UniqueWorker::MAX_TRIES 40: end 41: set << result 42: UniqueWorker.unique_map[key] = set 43: else 44: UniqueWorker.count_map ||= Hash.new() { 0 } 45: 46: key ||= UniqueWorker.key_for(&block) 47: result = block[UniqueWorker.count_map[key]] 48: UniqueWorker.count_map[key] += 1 49: end 50: 51: result 52: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.