Ruby - instance variable as class variable

YoloSnake

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?

Eric Duminil

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Access class variable from instance

Ruby class instance variable vs. class variable

Is the `@count` an instance variable or class variable in Ruby?

ruby access instance variable in instance_eval

ruby class instance variable configuration pattern

Assign module method to a Class variable or Instance variable

Class Variable as Instance of Enclosing Class

Python seems to treat instance variable as a class variable

Using python class variable vs instance variable

Get class of instance variable

How to access a class variable shadowed by an instance variable?

Refresh class instance variable that is set with ||=

Understanding the self keyword when referring to a class instance variable in a ruby?

How to initialize Ruby class instance variable to a new instance of another class?

ambiguous variable in a class instance

Class instance as class variable in python

Ruby instance variable changes unexpectedly

Saving instance list in class variable

Ruby - How to find class name given an instance variable?

Scope of instance variable on class methods

Ruby mark instance variable as unassignable

Ruby - set instance variable inside class method from string

How instance variable are related to class variable in python

Access instance variable of an implementation class

Class variable vs instance variable

Ruby class variable instance variable bug

Class instance variable not updating

Calling a parent instance variable from a sub class in ruby

Mypy with class variable that is an instance of the class

TOP Ranking

HotTag

Archive