logo       

Re: Sibling rivalry and class variables: msg#01194

lang.ruby.general

Subject: Re: Sibling rivalry and class variables


On Tue, 13 Aug 2002, Philip Mak wrote:

> What would you guys suggest I do if I want a variable set in the
> parent that the child may or may not override? So far, I've had to
> resort to using instance variables instead, like this:

This may or may not be what you are looking for, using class instance
variables. (The eval bit is just for conveninece.)


def class_attr_reader name
eval <<-EOF
def self.class_#{name}
return @#{name}
end
EOF
end

class Parent
class_attr_reader :info
@info = "parent"
def initialize
puts "Parent 1: Initializing #{(self.class).class_info}"
puts "Parent 2: in #{Parent.class_info}"
end
end

class Daughter < Parent
@info = "daughter"
def initialize
puts Daughter.class_info

super
end
end

class Son < Parent
@info = "son"
def initialize
puts Son.class_info
super
end
end

Parent.new
puts "---"
Daughter.new
puts "---"
Son.new






<Prev in Thread] Current Thread [Next in Thread>
Google Custom Search

News | FAQ | advertise