accessing superclass variables

  • Thread starter Nicolaj Soendberg Madsen
  • Start date
N

Nicolaj Soendberg Madsen

How do I access an outer variable from within a nested class?

Is it possible to directly access them?
 
M

Mohammad Khan

I am not sure what you wanted to know from your question.

Are you asking
How a variable of super class can be accessed from its sub-class?


Thanks
Mohammad
 
A

Ara.T.Howard

How do I access an outer variable from within a nested class?

Is it possible to directly access them?


jib:~ > cat a.rb
class Outer
CONST = 42
p CONST
class Inner
CONST = 42.0
p CONST
p Outer::CONST
p ::Outer::CONST
end
p Inner::CONST
end

p Outer::CONST
p Outer::Inner::CONST
p ::Outer::CONST
p ::Outer::Inner::CONST


jib:~ > ruby a.rb
42
42.0
42
42
42.0
42
42.0
42
42.0

initial '::' means 'start at the very top level. not needed here - but good to
know.

cheers.

-a
--
===============================================================================
| EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE :: 303.497.6469
| A flower falls, even though we love it;
| and a weed grows, even though we do not love it.
| --Dogen
===============================================================================
 
D

David A. Black

Hi --

jib:~ > cat a.rb
class Outer
CONST = 42
p CONST
class Inner
CONST = 42.0

[...]

Those are (Ruby's somewhat variable :) constants, though, not
variables.


David
 
N

Nicolaj Soendberg Madsen

Exactly!
That was my question. I would still appreciate any effort to explain me
how it works :)
 
R

Robert Klemme

Exactly!
That was my question. I would still appreciate any effort to explain me
how it works :)

Note though that the concept of nested class is something completely
different from sub class! The general advice is to use accessor methods
although you can access them directly. Consider this:

class Super
attr_accessor :foo

class Nested
def recommended(super_obj)
super_obj.foo
end

def direct(super_obj)
super_obj.instance_variable_get "@foo"
end
end
end

class Sub < Super
def direct; @foo; end
def recommended; foo; end
end


?> sub = Sub.new
=> "bar"


I am not sure what you wanted to know from your question.

Are you asking
How a variable of super class can be accessed from its sub-class?


Thanks
Mohammad

Regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,413
Latest member
KeiraLight

Latest Threads

Top