[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

private #initialize

Yossef Mendelssohn

11/27/2008 8:39:00 PM

My apologies if this has been discussed before, but I couldn't find
anything in a Google search, searching this particular list/group on
Google, or my first attempt at blade. (Later attempts complained about
not being able to access the index.)

So, in Ruby a private method is one that can only be called by the
object itself, and that's enforced by the simple rule of disallowing
an explicit receiver. Of course, there are ways around this; any
message can be passed if you just know what to do. Maybe I'm late to
the game, but I didn't realize it was okay to have #initialize be a
private method. More than that, I didn't realize #initialize was
*always* private. This confuses me because I think of SomeClass.new to
be

def new(*args, &block)
instance = allocate
instance.initialize(*args, &block)
instance
end

But that obviously can't be the case if #initialize is private.
Instead, it has to be

def new(*args, &block)
instance = allocate
instance.send(:initialize, *args, &block)
instance
end

It's a small change, but significant. And it seems odd to have
something this central to the language skirting the boundaries of
access control. Is it simply because an object shouldn't be re-
initialized once it's created? And if so, is that so horrible?

--
-yossef

1 Answer

Wayne Vucenic

11/27/2008 10:54:00 PM

0

On Thu, Nov 27, 2008 at 12:38 PM, Yossef Mendelssohn <ymendel@pobox.com> wrote:

> Is it simply because an object shouldn't be re-
> initialized once it's created? And if so, is that so horrible?

I don't think the issue is that an object shouldn't be re-initialized, I think
it's that (in general) an object shouldn't be re-initialized by anyone
except itself. If I'm writing a class, I'll declare certain instance methods
private, because I don't want clients calling them. initialize seems like
a method that I rarely want clients to be able to call.

Best regards,

Wayne

---
Wayne Vucenic
No Bugs Software
Agile Ruby (but preferably not Rails) Contract Programming in Silicon
Valley since 2001