Usenet.com

www.Usenet.com

Group Index

Comp Thread Archive from Usenet.com

<-- __Chronological__ --> <-- __Thread__ -->

Re: General Ruby Programming questions



On Thu, 2003-10-16 at 13:06, Gavin Sinclair wrote:
> > [Simon wrote:]
> >
> >> > (c) how invoke "hidden" methods?
> >>
> >> Simply send the message a method invocation would produce yourself:
> >>
> >> irb(main):003:0> 5.send(:rand)
> >> => 0.748920713318512
> >
> > Whoa! So private methods can be called after all???!
> >
> > Not the end of the world, I guess. After all, Python doesn't support
> > private methods at all, right? Still a bit odd in my opinion.
> >
> > Is there any reason why Ruby allows private methods to be invoked like
> > this? (rather than provide a tidy alternative for problems like mine).
> 
> It may help to think of it not as a method being invoked, rather a message
> being sent.  The object decides how it wishes to respond to that message.
> 
> After all, you can't invoke a method that doesn't exist, but you can get a
> response back from a message that doesn't have a corresponding method, if
> you get my drift.

Yes, that's clear.

However I could still rephrase my original question as:

  Why doesn't ruby throw a NoMethodError exception when a message is
  sent to a method which is private using the "send" feature?

The purpose of marking a method as private is to indicate that the only
valid invocation of the code within that method is when the invoker is
another method on the same class (java convention) or the same object
(ruby convention). 

Quite often private methods don't preserve class invariants. And
exposing methods that can break class invariants to the outside world is
never a good idea.

As I said, it's no big deal.  Perl, javascript and (as far as I know)
Python don't support the concept of private methods at all. 

However I am curious to know if there is a real justification for
allowing private methods to be invoked via "send", or if it just an
accident that this works. Ruby takes encapsulation so seriously in many
other ways...

Cheers,

Simon

PS: I did eventually find that class lookup implementation on the wiki.
I think it would be really nice to have this in the std libs (eg as a
class method on the Class or Object classes).

http://www.rubygarden.org/ruby?FindClassesByName

def get_class(name)
  name.split(/::/).inject(Object) {|p,n|
    p.const_get(n)
  }
end





<-- __Chronological__ --> <-- __Thread__ -->


Usenet.com

Please check out one of the Premium USENET Services below: