From: Igor Pirnovar Date: 2013-04-01T15:16:13+09:00 Subject: Re: Private setters can be called by self, why not getters? Josh Cheek wrote in post #1103861: > (b/c I was going to recommend making these protected instead of private, > in order to avoid this issue). > > -Josh You are right, making these protected instead of private seems to be the best solution, unless you need to shield access to your getters and setters from subclasses too. Taking into account, that instance variables in Ruby are by design public, all this accessor encapsulation is rather 'non-ruby-ish', nevertheless, your suggestion deserves to be noticed! The following code works exactly as expected, and you can even use only the simplest form of accessor declaration {{ attr_accessor :count }} in the private section, without bothering to separate the getter from the setter method. -------------------------------------------------------------------- #!/usr/bin/env ruby class Counter def initialize; self.count = 0; end def show_count; puts "Count=#{count}"; end def increment1; self.count = count + 1; end def increment2; self.count = self.count + 1; end def increment3; self.count += 1; end protected attr_accessor :count end o = Counter.new o.show_count #=> Count=0 o.increment1 o.show_count #=> Count=1 o.increment2 o.show_count #=> Count=2 o.increment3 o.show_count #=> Count=3 puts "Explicit get: Count=#{o.count}" #=> fails with exception o.count=1234 #=> would properly fail too -------------------------------------------------------------------- Very good, Josh! Regards, igor -- Posted via http://www.ruby-forum.com/.