相关疑难解决方法(0)

Ruby类实例变量与类变量

我读过" Ruby实例变量什么时候设置? "但我在使用类实例变量时有两种想法.

类变量由类的所有对象共享,实例变量属于一个对象.如果我们有类变量,那么使用类实例变量的余地就不大了.

有人可以解释这两者之间的区别以及何时使用它们?

这是一个代码示例:

class S
  @@k = 23
  @s = 15
  def self.s
    @s
  end
  def self.k
     @@k
  end

end
p S.s #15
p S.k #23
Run Code Online (Sandbox Code Playgroud)

我现在明白了,Class Instance Variables不会传递给继承链!

ruby instance-variables class-variables class-instance-variables

172
推荐指数
6
解决办法
11万
查看次数

Ruby:继承使用类变量的代码

情况:我有多个类,每个类应该包含一个带有配置哈希的变量; 每个类的不同哈希,但对于类的所有实例都是相同的.

起初,我试过这样的

class A
  def self.init config
    @@config = config
  end

  def config
    @@config
  end
end

class B < A; end
class C < A; end
Run Code Online (Sandbox Code Playgroud)

但很快就注意到它不会那样工作,因为@@ config是在A的上下文中保存,而不是B或C,因此:

B.init "bar"
p B.new.config  # => "bar"
p C.new.config  # => "bar" - which would be nil if B had it's own @@config

C.init "foo"
p B.new.config  # => "foo" - which would still be "bar" if C had it's own @@config
p C.new.config  # => "foo"
Run Code Online (Sandbox Code Playgroud)

我想过像这样使用它:

modules = [B, …
Run Code Online (Sandbox Code Playgroud)

ruby inheritance metaprogramming class

42
推荐指数
1
解决办法
2万
查看次数