ruby - 在 Ruby 中覆盖实例变量数组的运算符

标签 ruby operators operator-overloading

对不起,我的标题不好,我真的不知道该怎么调用它。

我在 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/

相关文章:

c# - 您如何看待 C# 中的 ??= 运算符?

c++ - 重载运算符<< c++;对 `std::basic_ostream 的 undefined reference

mysql - 更高效的事件记录分组

ruby-on-rails - 如何给 .irbrc 添加别名?

mysql - Rails ActiveRecord,从连接表中选择不同的字段并返回所有模型

ruby - 使用 Ruby 从公共(public) Google 日历获取数据

php - 你知道一个很好的 PHP hack 来做内联条件分配吗?

c++ - 运算符重载和类型转换

c++ - 为模板类重载运算符<<

c# - "ulong == ulong?"评估为 "ulong == ulong"工作正常