Search code examples
rubyclassinstance-variables

Ruby - instance variable as class variable


I have a class:

class Foo

  def self.test
    @test
  end

  def foo
    @test = 1
    bar
  end

  private

  def bar
    @test = 2
  end
end

object = Foo.new.foo
Foo.test

# => nil

The only way I could get it to output '2' is by making @test a class variable. Is there any other way around using the instance variable and being able to display it with Foo.test?


Solution

  • It's not really clear to me what you want to achieve, and why. Here's an example with a "class instance variable". It might be what you're looking for:

    class Foo
      class << self
        attr_accessor :test
      end
    
      attr_accessor :test
    
      def foo
        @test = 1
        bar
      end
    
      private
    
      def bar
        Foo.test = 2
      end
    end
    
    foo = Foo.new
    foo.foo
    p foo.test
    #=> 1
    p Foo.test
    #=> 2