1

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?

2
  • Foo.test which is a class method has no access to instance variables. Commented Jul 15, 2017 at 10:24
  • 1
    What's your real goal? You're using different objects, so they obviously don't have access to the same instance variables. Commented Jul 15, 2017 at 10:52

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

You commented at the same time with me lol. Well that was the purpose of the question, how to avoid using @@ but having the same result. My version is a little bit different though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.