30 Days of Tech: Day 14 - Minlength Enum
June 14th, 2008
Here’s a hack I cooked up some time ago for situations where you want an enumerable with a minimum length. It decorates an existing enum instance (an object supporting the each method) to contain a minimum number of objects, returning a “filler” object if the end of the wrapped enum is reached before hitting the minimum length. It’s probably easier understood through a simple code example.
MinLengthEnum.new(4,[1,2],"filler").to_a #=> [1, 2, "filler", "filler"]
And then the implementation, which is quite simple
class MinLengthEnum
include Enumerable
def initialize(length,enum,filler = nil)
@length = length
@enum = enum
@filler = filler
end
def each
filler = [@filler] * @length
@enum.each {|o| yield o; filler.shift}
filler.each {|o| yield o}
end
end
There you have it. Nothing special, but something. Have a great day!
Sorry, comments are closed for this article.