Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created October 10, 2011 06:42
Show Gist options
  • Save d11wtq/1274760 to your computer and use it in GitHub Desktop.
Save d11wtq/1274760 to your computer and use it in GitHub Desktop.
class CoercedArray < Array
def initialize(type)
super()
@type = type
end
def push(object)
object = @type.new(object) unless object.kind_of?(@type)
super
end
def <<(object)
push(object)
end
def concat(other)
raise ArgumentError, "Cannot append #{other.class} to #{self.class}<#{@type}>" unless other.kind_of?(Array)
super(other.inject(CoercedArray.new(@type)) { |ary, v| ary.push(v) })
end
alias :"+=" :concat
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment