class Animal
attr_accessor :state
@state=:alive
class Dog
# I want to access the @state in here
end
class Cat
# I want to access the @state in here
end
end
The way i see to get this to work:
class Animal
class << self
attr_accessor :state
end
@state=:alive
class Dog
class << self
attr_reader :state
end
def self.state
Animal.state
end
end
end
Animal.state=:dead
puts Animal::Dog.state
The classes aren’t related by inheritance, only namespace.
If you want to link them properly, you’ll need:
class Dog < Animal
Now the problem is… I know only the first class name in runtime so how
can i express Animal dynamically
This should work.
class Animal
@state = :alive
def self.state?
@state.to_s
end
class Dog
# I want to access the @state in here
def initialize
puts 'state is: '+Animal.state?
end
end
@state = :dead
class Cat
# I want to access the @state in here
def initialize
puts 'state is: '+Animal.state?
end
end
end
Animal::Dog.new
Animal::Cat.new