2017-07-15 39 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