Trying to "inherit" class configuration and modify it

W

Wayne Walker

This gist has a bigger example of what I'm trying to do, but just
understanding how to make the following short example work, and/or why
it doesn't, will probably get me through the bigger problem.

testit.rb:

require 'pp'
class A
@@a = [7]
def self.get_a
@@a
end
def self.put_a
pp @@a
end
end

class B < A
@@a = A.get_a.dup
@@a = [8]
def self.put_a
pp @@a
end
end

A.put_a
B.put_a
A.put_a

[wwalker@dogwood inherit_settings] $ ruby testit.rb
[8]
[8]
[8]

I would expect:
[7]
[8]
[7]

I don't see my error. I think that maybe dup() doesn't work on a class
variable, or that maybe class variables are not really class variables,
but are rather hierarchy variables that can only exist in one place in
an class and it ancestry?

--

Wayne Walker
(e-mail address removed)
(512) 633-8076
Senior Consultant
Solid Constructs, LLC
 
B

Brian Candler

Wayne Walker wrote in post #980677:
maybe class variables are not really class variables,
but are rather hierarchy variables that can only exist in one place in
an class and it ancestry?

That's exactly it. Class variables are something of a misfeature in
Ruby.

However, in Ruby everything is an object - including a Class. So you can
use a regular instance variable of the class itself. Just change all
'@@'s to '@' in your code, and it will work the way you want.

To access the value from an instance method, use

self.class.get_a

(because 'class' is otherwise a keyword)

HTH,

Brian.
 

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

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top