1

在一个 Array 子类(只是一个对输入值进行强制转换的数组)中,我已定义#concat为确保值被强制转换。由于没有人使用#concat并且更有可能使用#+=我尝试别名#+=to #concat,但它似乎从未被调用。有任何想法吗?

请注意,强制实际上总是针对特定超类的对象(通过构造函数接受输入),以防此代码似乎没有按照我的描述进行。它是内部私有 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工作正常,但#+=似乎完全被绕过了。

4

1 回答 1

5

因为a += b是语法糖,a = a + b所以我会尝试覆盖该+方法。

于 2011-10-10T06:52:41.697 回答