Ruby - 实例变量作为类变量

时间:2017-07-15 10:20:16

标签: ruby class instance-variables

我有一个班级:

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显示它?

2 个答案:

答案 0 :(得分:1)

我不清楚你想要实现什么,以及为什么。这是一个带有“类实例变量”的示例。这可能是你在寻找的东西:

enums

答案 1 :(得分: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

你重写了这个类:

FinalityFlow
相关问题