2017-07-15 95 views
0

我有一个类:红宝石 - 实例变量的类变量

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 

我能得到它的输出只有这样,“2”是通过使@test类变量。是否有任何其他方式使用实例变量,并能够用Foo.test显示它?

+0

'Foo.test'这是一类方法实例变量的访问权限。 –

+0

@霍曼这就是为什么我问,使用'@@测试'很容易,但被认为是'代码味道'。然后我必须使用类实例变量。 – YoloSnake

+1

你真正的目标是什么?你使用的是不同的对象,所以他们显然不能访​​问相同的实例变量。 –

回答

1

我不清楚你想达到什么目的,为什么。这里有一个“类实例变量”的例子。这可能是你在找什么:

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 
+0

你在同一时间与我评论哈哈。那么这就是问题的目的,如何避免使用@@但是具有相同的结果。虽然我的版本有点不同。 – YoloSnake

0

,是因为使用@@(类变量)被认为是一个“代码味道”,你应该使用一个类的实例变量来代替。 您可以通过添加这样做:

class << self 
     attr_accessor :test 
end 

你重写类是这样的:

class Foo 

    class << self 
    attr_accessor :test 
    end 

    def foo 
    Foo.test = 1 
    bar 
    end 

    private 

    def bar 
    Foo.test = 2 
    end 
end 

object = Foo.new.foo 
Foo.test 

# => 2