在Ruby中覆盖实例变量数组的运算符 [英] Overriding instance variable array's operators in Ruby
本文介绍了在Ruby中覆盖实例变量数组的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对不起,标题不好,我真的不知道该怎么称呼.
Sorry for the poor title, I don't really know what to call this.
我在Ruby中有这样的东西:
I have something like this in 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)
作为类中的一种方法,但是没有用.
For the @my_array
instance variable, I want to override the <<
operator so that I can first process whatever is being inserted to it. I've tried @my_array.<<(value)
as a method in the class, but it didn't work.
推荐答案
我认为您正在寻找这个东西:
I think you're looking for this:
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
了解Ruby Singleton上有一篇很好的文章,介绍了相关主题类.
这篇关于在Ruby中覆盖实例变量数组的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文