[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

simple subclass question

Ball, Donald A Jr (Library)

5/1/2007 3:30:00 PM

If I want a class and its children to have different values for the same
class variables, how would I go about making that happen?

- donald

2 Answers

Robert Dober

5/1/2007 3:43:00 PM

0

On 5/1/07, Ball, Donald A Jr (Library) <donald.ball@nashville.gov> wrote:
> If I want a class and its children to have different values for the same
> class variables, how would I go about making that happen?
>
> - donald
>
>
Hi Donald, has been a long time...

504/4 > cat subclass-vars.rb && ruby subclass-vars.rb
#!/usr/bin/ruby
# vim: sts=2 sw=2 nu expandtab tw=0:
#
P = Class.new { @a = 42 }
class << P
attr_accessor :a
end

S = Class.new P

puts P.a
puts S.a
S.a = 43
puts P.a
puts S.a
------>
42
nil
42
43

Hopefully I understood what you wanted.

Cheers
Robert
--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw

Daniel Lucraft

5/1/2007 3:50:00 PM

0

Ball, Donald A Jr (Library) wrote:
> If I want a class and its children to have different values for the same
> class variables, how would I go about making that happen?
>
> - donald

Instead of:

class A
def A.var=(v)
@@var = v
end
def A.var
@@var
end
end

class B < A
end

where A and B will share the class variable, use a class instance
variable instead:

class A
def A.var=(v)
@var = v
end
def A.var
@var
end
end

class B < A
end

where A and B will have different class instance variables.

You can use the attr_accessor notation to create class instance variable
getters and setters like this:

class A
class << self
attr_accessor :var
end
end

best,
Dan

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