Ruby 变量声明:“变量”之间的差异@@&引用;及;类<&书信电报;“自我”;
这是我的测试程序:Ruby 变量声明:“变量”之间的差异@@&引用;及;类<&书信电报;“自我”;,ruby,class,variables,scope,static,Ruby,Class,Variables,Scope,Static,这是我的测试程序: module Foo @@bar1 = "1" # static property of the module? class << self # open static section @bar2 = "2" # property in static section, should be static property? def func1 # static function puts "bar1: #{@@bar1}"
module Foo
@@bar1 = "1" # static property of the module?
class << self # open static section
@bar2 = "2" # property in static section, should be static property?
def func1 # static function
puts "bar1: #{@@bar1}"
puts "bar2: #{@bar2}"
end
end
end
Foo.func1
我的问题是,bar1
和bar2
的声明有什么区别
我以为
- 将
添加到@
(另外,您不能有模块的实例,对吗?)bar1
- 首先将
放在bar2
类中,让我们忘记单例类(
因此,不建议使用模块/类变量 让我们进一步讨论一下模块/类实例变量的行为 在Ruby中,模块和类都是对象,因此它们可以像普通对象一样拥有自己的实例变量。模块/类中的这些实例变量称为模块/类实例变量 在Ruby中,实例变量只属于主机对象,其他对象看不到它(至少不使用元编程技巧) 一个类和该类的一个实例是两个不同的对象,所以实例不能访问类实例变量。一个类和它的一个子类是两个不同的对象,所以它们不能相互访问类实例变量 最后,让我们谈谈单例类 每个对象都有它的单例类。这个单例类只有一个实例-对象 模块和类是对象,因此它们可以有自己的单例类类“foo in child” Parent.bar#=>“Parent中的bar”
类,这是一个很好的演示,说明了为什么正确使用这些工具会如此棘手。很好!
$ ruby test.rb bar1: 1 bar2:
class X @@foo = 'foo' # a class variable @bar = 'bar' # a class instance variable def self.foo @@foo end def self.bar @bar end def foo @@foo end def bar @bar end end X.foo #=> "foo" X.bar #=> "bar" X.new.foo #=> "foo" X.new.bar #=> nil
class Parent @@foo = 'foo in parent' @bar = 'bar in parent' def self.foo @@foo end def self.bar @bar end end class Child < Parent @@foo = 'foo in child' @bar = 'bar in child' end Parent.foo #=> "foo in child" Parent.bar #=> "bar in parent"