gpt4 book ai didi

ruby - 尝试在 Array 子类中重新定义 += 似乎没有任何作用?

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:36 25 4
gpt4 key购买 nike

在 Array 子类(只是一个对输入值进行某些强制转换的数组)中,我定义了 #concat 以确保强制转换值。由于没有人使用过 #concat 并且更有可能使用 #+= 我尝试将 #+= 别名为 #concat,但它似乎永远不会被调用。有什么想法吗?

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

最佳答案

a += ba = a + b 的语法糖我会尝试覆盖 +方法。

关于ruby - 尝试在 Array 子类中重新定义 += 似乎没有任何作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7709321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com