Initialize

Should initialize() be public, private or protected, and why?

Thanks

···

--
Jonathan Leighton
http://turnipspatch.com/ | http://jonathanleighton.com/ | http://digital-proof.org/

Should initialize() be public, private or protected, and why?

moulon% cat b.rb
#!/usr/bin/ruby
class A
   protected
   def initialize
   end
end

p A.private_instance_methods(false)
p A.protected_instance_methods(false)
moulon%

moulon% ./b.rb
["initialize"]

moulon%

Guy Decoux

Thanks for the reply. Forgive me, but I don't understand what the point
is in your example? Or why initialize is returned by
private_instance_methods() but not protected_instance_methods()? Could
you elaborate a bit please?

Thanks

···

On Sun, 2006-01-01 at 23:06 +0900, ts wrote:

> Should initialize() be public, private or protected, and why?

moulon% cat b.rb
#!/usr/bin/ruby
class A
   protected
   def initialize
   end
end

p A.private_instance_methods(false)
p A.protected_instance_methods(false)
moulon%

moulon% ./b.rb
["initialize"]

moulon%

--
Jonathan Leighton
http://turnipspatch.com/ | http://jonathanleighton.com/ | http://digital-proof.org/

Thanks for the reply. Forgive me, but I don't understand what the point
is in your example? Or why initialize is returned by
private_instance_methods() but not protected_instance_methods()? Could
you elaborate a bit please?

#initialize (like #initialize_copy) is *always* a private method. Even if
  you try to define it as public or protected, ruby will make it a private
  method.

Guy Decoux

#initialize (like #initialize_copy) is *always* a private method. Even if
  you try to define it as public or protected, ruby will make it a private
  method.

Well, there is an exception when you redefine its state after the creation

moulon% cat b.rb
#!/usr/bin/ruby
class A
   def initialize
   end
   protected :initialize
end

A.new
moulon%

moulon% ./b.rb
./b.rb:8:in `new': protected method `initialize' called for #<A:0xb7d64e94> (NoMethodError)
  from ./b.rb:8
moulon%

Guy Decoux

Ah, okay, thanks.

···

On Mon, 2006-01-02 at 00:53 +0900, ts wrote:

> Thanks for the reply. Forgive me, but I don't understand what the point
> is in your example? Or why initialize is returned by
> private_instance_methods() but not protected_instance_methods()? Could
> you elaborate a bit please?

#initialize (like #initialize_copy) is *always* a private method. Even if
  you try to define it as public or protected, ruby will make it a private
  method.

--
Jonathan Leighton
http://turnipspatch.com/ | http://jonathanleighton.com/ | http://digital-proof.org/