From: Ross Bamford Date: 2006-01-21T09:46:20+09:00 Subject: Re: Protected methods and class methods On Sat, 2006-01-21 at 04:34 +0900, Gioele Barabucci wrote: > Now I'm facing a problem. I use some static methods as "factory methods", to > create "prefilled" class instances. These methods can't access the protected > methods of the same class. Is this behavior intentional? I believe so. Because the class Info is itself an instance of Class, while the instance is an instance of Info, which is entirely unrelated to Class (apart from the common ancestor, Object). So there's no reason for protected instance methods on Info to be available to methods on the class itself. (I think static methods are usually referred to as class methods in Ruby. *nothing* is static here). Access modifiers can be pretty surprising depending where you're coming from. Check out (if you haven't already): http://www.whytheluckystiff.net/ruby/pickaxe/html/tut_classes.html#S4 > Is there clean solution to this problem? If not, how can I work around this > problem? This is a public class, so I don't want to add other params > to initialize. > I get this error > > irb(main):032:0> Info.fromBytes("\010\008") > NoMethodError: protected method `length=' called for # @length=nil, @typeID=8> > from (irb):23:in `fromBytes' > > with this class > > [ ... snipped ...] Maybe try this workaround. I've also changed a few things to be more 'Rubyish', but you can just ignore that if you like :) class Info def initialize(type_id) @type_id = type_id @length = nil end attr_reader :type_id def length @length ||= very_long_math_calcs end def Info.from_bytes(bytes) type_id = bytes[0,1].unpack("c")[0] len = bytes[1,1].unpack("c")[0] info = Info.new(type_id) info.instance_eval { self.length = len } ## <<< changed! # or (if you don't care about encapsulation here): # info.instance_eval { @length = len } info end # maybe don't need this now? protected attr_writer :length end # Noticed a potential error in your input - \008 isn't valid octal :) p Info.from_bytes("\010\015") #=> # Hope that helps, Ross -- Ross Bamford - rosco@roscopeco.REMOVE.co.uk