有没有办法在Ruby中覆盖<<运算符?

Joh*_*ker 10 ruby overriding ruby-on-rails

我正在尝试做类似的事情:

account.users << User.new
Run Code Online (Sandbox Code Playgroud)

但我需要用户成为帐户的一种方法.所以我尝试过这样的事情:

def users<<(obj)
Run Code Online (Sandbox Code Playgroud)

但我没有运气.这甚至可以用Ruby做吗?我会假设,因为ActiveRecord关系似乎在Rails中以这种方式工作.

Jes*_*ott 9

检查这个答案:Rails:覆盖ActiveRecord关联方法

[此代码完全来自其他答案,此处为未来的搜索者]

has_many :tags, :through => :taggings, :order => :name do
    def << (value)
      "overriden" #your code here
    end     
  end
Run Code Online (Sandbox Code Playgroud)


muf*_*sta 5

看起来您可能没有描述您的实际问题,但回答您的问题 - 是的,您可以覆盖<<运营商:

class Foo
  def <<(x)
    puts "hi! #{x}"
  end
end

f = Foo.new
=> #<Foo:0x00000009b389f0>
> f << "there"
hi! there
Run Code Online (Sandbox Code Playgroud)


shi*_*ara 1

在本例中,它是<<您用户的类别。所以可以是 anArray或 a AssociationProxy。

最简单的就是创建一个新方法来完成您想要的操作。

您可以通过实例重写该方法。

account.users.instance_eval do
  def <<(x)
    put 'add'
  end
end

account.users << User.new
# add
Run Code Online (Sandbox Code Playgroud)

但是在添加 << 之前你需要一直这样做