ruby - Setting instance variables on different objects of the same class -


let's have class called person , person has attribute called partner. when call partner= on 1 of person objects, want set @partner instance variable of both objects. here's example invalid syntax:

class person    attr_reader :partner    def partner=(person)      # reset old partner instance variable if exists     partner.@partner = nil if partner      # set partner attributes     @partner = person     person.@partner = self   end end 

change attr_reader attr_accessor , add helper method:

class person    attr_accessor :partner    def link_partners(person)     @partner = person     person.partner = self   end end 

update visibility. based on suggestion frederick below. little more verbose, prevent partner being set directly:

class person   protected   attr_writer :partner    public   attr_reader :partner    def link_partners(person)     @partner = person     person.partner = self   end end 

both implementations works this:

p1, p2 = person.new, person.new p1.link_partners(p2)  # p2.link_partners(p1) 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -