Is there a way to override the << operator in Ruby? Is there a way to override the << operator in Ruby? ruby ruby

Is there a way to override the << operator in Ruby?


Check this answer: Rails: Overriding ActiveRecord association method

[this code is completely from the other answer, here for future searchers]

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


It seems like you might not be describing your actual problem, but to answer your question -- yes you can override the << operator:

class Foo  def <<(x)    puts "hi! #{x}"  endendf = Foo.new=> #<Foo:0x00000009b389f0>> f << "there"hi! there


I assume you have a model like this:

class Account < ActiveRecord::Base  has_and_belongs_to_many :usersend

To override Account#users<<, you need to define it in a block that you pass to has_and_belongs_to_many:

class Account < ActiveRecord::Base  has_and_belongs_to_many :users do    def <<(user)      # ...    end  endend

You can access the appropriate Account object by referring to proxy_association.owner:

def <<(user)  account = proxy_association.ownerend

To call the original Account#users<<, call Account#users.concat:

def <<(user)  account = proxy_association.owner  # user = do_something(user)  account.users.concat(user)end

For more details, see this page: Association extensions - ActiveRecord