[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

wacky?) protected behavior

David Weldon

1/3/2007 11:00:00 PM

class Foo
def store(o)
o.dave=1
end
end
class SubFoo < Foo
def initialize
@dave=2
end
def store
super(self)
end
protected
attr_accessor :dave
end
sf = SubFoo.new
sf.store
p sf

The above code executes and shows that sf.dave has been set to 1. I
assumed it would not work because I thought Foo should not have access
to protected members which were defined in its subclasses. Is this a
bug? If not, can someone explain why this works? Thanks!

--
Posted via http://www.ruby-....

4 Answers

Trans

1/4/2007 12:20:00 AM

0


David Weldon wrote:
> class Foo
> def store(o)
> o.dave=1
> end
> end
> class SubFoo < Foo
> def initialize
> @dave=2
> end
> def store
> super(self)
> end
> protected
> attr_accessor :dave
> end
> sf = SubFoo.new
> sf.store
> p sf
>
> The above code executes and shows that sf.dave has been set to 1. I
> assumed it would not work because I thought Foo should not have access
> to protected members which were defined in its subclasses. Is this a
> bug? If not, can someone explain why this works? Thanks!

But youre calling store from the subclass.

T.


David Weldon

1/4/2007 1:07:00 AM

0

Trans wrote:
> But youre calling store from the subclass.

I gather what you mean is that o.dave=1 is executed from the context of
a SubFoo and not from the context of a Foo. I guess thats how Ruby works
but it doesn't seem intuitive to me because I'm not sure the equivalent
code would work in other languages I'm familiar with - namely Java and
C++.

--
Posted via http://www.ruby-....

Trans

1/4/2007 1:37:00 AM

0


David Weldon wrote:
> Trans wrote:
> > But youre calling store from the subclass.
>
> I gather what you mean is that o.dave=1 is executed from the context of
> a SubFoo and not from the context of a Foo. I guess thats how Ruby works
> but it doesn't seem intuitive to me because I'm not sure the equivalent
> code would work in other languages I'm familiar with - namely Java and
> C++.

Thats right. I can say about th eother languages buit try this:

class Foo
def store(o)
p self # who am I?
o.dave=1
end
end
class SubFoo < Foo
def initialize
@dave=2
end
def store
super(self)
end
protected
attr_accessor :dave
end
sf = SubFoo.new
sf.store
p sf

T.


Jacob Fugal

1/4/2007 5:50:00 PM

0

On 1/3/07, David Weldon <dweldon@gmail.com> wrote:
> Trans wrote:
> > But youre calling store from the subclass.
>
> I gather what you mean is that o.dave=1 is executed from the context of
> a SubFoo and not from the context of a Foo. I guess thats how Ruby works
> but it doesn't seem intuitive to me because I'm not sure the equivalent
> code would work in other languages I'm familiar with - namely Java and
> C++.

Ruby != Java && Ruby != C

Jacob Fugal