在 Ruby 中重写实例变量数组的运算符
抱歉,这个标题不好,我真的不知道该怎么称呼它。
我在 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)
作为类中的方法,但它不起作用。
Sorry for the poor title, I don't really know what to call this.
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!"
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我想您正在寻找这个:
了解 Ruby Singleton 类。
I think you're looking for this:
There's a good article about this and related topics at Understanding Ruby Singleton Classes.
我不确定这实际上是你可以直接做的事情。
您可以尝试从
Array
创建一个派生类,实现您的功能,例如:I'm not sure that's actually something you can do directly.
You can try creating a derived class from
Array
, implementing your functionality, like:干得好...
Here you go...
非常hackish,并且超出了我的想象......
只需用您想要执行的任何预处理更改“投入价值”即可。
Very hackish, and off the top of my head ...
Just change 'puts value' with whatever preprocessing you want to do.
您可以扩展任何单个对象的元类,而无需创建全新的类:
You can extend the metaclass of any individual object, without having to create a whole new class:
我扩展了该类,创建了一个提供对实例变量的访问的方法。
i extend the class, creating a method which provides access to the instance variable.