对不起,我的标题不好,我真的不知道该怎么调用它。
我在 Ruby 中有这样的东西:
class Test
def initialize
@my_array = []
end
attr_accessor :my_array
end
test = Test.new
test.my_array << "Hello, World!"
对于 @my_array
实例变量,我想覆盖 <<
运算符,以便我可以首先处理插入到其中的任何内容。我试过了 @my_array.<<(value)
作为类中的方法,但它不起作用。
最佳答案
我想你正在寻找这个:
class Test
def initialize
@myarray = []
class << @myarray
def <<(val)
puts "adding #{val}" # or whatever it is you want to do first
super(val)
end
end
end
attr_accessor :myarray
end
在 Understanding Ruby Singleton Classes 上有一篇关于这个和相关主题的好文章.
关于ruby - 在 Ruby 中覆盖实例变量数组的运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1656090/