Forum: Ruby How to access a property of a class inside a subclass

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
97334b75c93574ed3e514f33849f0953?d=identicon&s=25 Mario Ruiz (tcblues)
on 2016-10-12 11:42
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
97334b75c93574ed3e514f33849f0953?d=identicon&s=25 Mario Ruiz (tcblues)
on 2016-10-12 12:50
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
97334b75c93574ed3e514f33849f0953?d=identicon&s=25 Mario Ruiz (tcblues)
on 2016-10-12 14:58
Now the problem is... I know only the first class name in runtime so how
can i express Animal dynamically
14b5582046b4e7b24ab69b7886a35868?d=identicon&s=25 Joel Pearson (virtuoso)
on 2016-10-12 20:35
The classes aren't related by inheritance, only namespace.

If you want to link them properly, you'll need:

class Dog < Animal
4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2016-10-20 22:59
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
This topic is locked and can not be replied to.