可能在Ruby中重载<<操作符?

时间:2018-11-01 15:45:33

标签: ruby

我想重载<<操作符,如下所示:

class A
    attr_accessor :secret_array

...
# assume the array gets initialized at some point
...

    def public_array
        # when it's an rvalue, load it from cache
        load_array_from_cache
    end

    def public_array << (what)
        # but when it's an lvalue, send it to the secret array
        secret_array << what
    end

end

我的代码显然不能正常工作,但是这可能吗?如果可以,语法是什么?

谢谢, 凯文

1 个答案:

答案 0 :(得分:1)

class A
  def initialize
    @secret_array = []
  end

  def public_array
    @secret_array
  end

  def <<(what)
    @secret_array << what
    self
  end
end

a = A.new
# => #<A:0x000055e10943df60 @secret_array=[]> 
a << 'q' << 'w' << 'r'
# => #<A:0x000055e10943df60 @secret_array=["q", "w", "r"]> 
a.public_array
# => ["q", "w", "r"]