[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Visibility and the "self" receiver

M. Maniak

5/16/2005 12:04:00 AM

Hello,

I'm new to Ruby (coming from Java) and puzzled
by the behaviour of "self" when defining a private method:

-->Snip
class TestClass

def initialize(args)
@myString = args
self.print()
end

private
def print()
puts @myString
end
end
-->Snip

This produces a NameError when instantiated/executed.
Without reference to itself (without "self") everything works...

I guess print() is then treated as a function and not as
a method (whatever that means in OOP -> maybe no return value).

I know that in Java "this" is a somehow comparable reference
with "self" in Ruby and denotes the actual object. I use it
quite often...

Has anyone an explanation about this specific behaviour (I know
it's not a bug)? Maybe I don't get the principle of "private"
or Visibility in general in Ruby.

Thank you very much for a hint.

Greets,
M. Maniak
3 Answers

dblack

5/16/2005 12:19:00 AM

0

Mark Hubbart

5/16/2005 12:25:00 AM

0

On 5/15/05, M. Maniak <skull2crush@hotmail.com> wrote:
> Hello,
>
> I'm new to Ruby (coming from Java) and puzzled
> by the behaviour of "self" when defining a private method:

try:

> -->Snip
> class TestClass
>
> def initialize(args)
> @myString = args
> print()
> end
>
> private
> def print()
> puts @myString
> end
> end
> -->Snip

... which should work.

> This produces a NameError when instantiated/executed.
> Without reference to itself (without "self") everything works...
>
> I guess print() is then treated as a function and not as
> a method (whatever that means in OOP -> maybe no return value).
>
> I know that in Java "this" is a somehow comparable reference
> with "self" in Ruby and denotes the actual object. I use it
> quite often...
>
> Has anyone an explanation about this specific behaviour (I know
> it's not a bug)? Maybe I don't get the principle of "private"
> or Visibility in general in Ruby.

Private methods can only be called without an explicit receiver. This
means that they can only be called when the implicit receiver is
"self", and no receiver is specified:

class A
private
def a() :a end
end

A.new.a #==> error, a is private and called with an explicit receiver.
A.new.instance_eval do #==> changes self to A.new for this block
self.a #==> error, explicit receiver
a #==> no error, implicit receiver is self
end

HTH,
Mark

> Thank you very much for a hint.
>
> Greets,
> M. Maniak
>
>


M. Maniak

5/16/2005 1:40:00 AM

0

Oh well, that seems to explain it...

Thank you very much kind people of the Ruby Mailing list.

Greetings from Switzerland