In an Array subclass (just an array that does some coercing of input values) I’ve defined #concat to ensure values are coerced. Since nobody ever uses #concat and is more likely to use #+= I tried to alias #+= to #concat, but it never seems to get invoked. Any ideas?
Note that the coercing is actually always to objects of a particular superclass (which accepts input via the constructor), in case this code seems not to do what I describe. It’s part of an internal, private API.
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
#concat is working correctly, but #+= seems to be completely by-passed.
Since
a += bis syntactic sugar fora = a + bI’d try to overwrite the+method.