Ruby - 实例变量作为 class 变量
Ruby - instance variable as class variable
我有一个 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
我让它输出“2”的唯一方法是使 @test
成为 class 变量。有没有其他方法可以使用实例变量并能够用 Foo.test
?
显示它
我不太清楚你想要实现什么,为什么。这是一个带有 "class instance variable" 的示例。这可能是您正在寻找的:
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
我有一个 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
我让它输出“2”的唯一方法是使 @test
成为 class 变量。有没有其他方法可以使用实例变量并能够用 Foo.test
?
我不太清楚你想要实现什么,为什么。这是一个带有 "class instance variable" 的示例。这可能是您正在寻找的:
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