Ruby中的类常量和类实例变量有什么区别?

时间:2018-03-14 21:59:08

标签: ruby inheritance

我会注意到,有很多类似措辞的问题与我认为的问题截然不同。

以下功能方面有什么区别?例如。他们在继承方面的表现如何?

class Foo
  BAR = 'Hello'
end

class Foo
  @bar = 'Hello'
end

1 个答案:

答案 0 :(得分:4)

访问

默认情况下,常量是公开的(我们在这里忽略private constants)。没有读者和/或编写器方法,类实例变量是不可访问的(除了像Object#instance_variable_get这样的东西,但通常不是很好的样式)。

继承

常量将引用它们使用的上下文中的值,而不是self的当前值。例如,

class Foo
  BAR = 'Parent'

  def self.speak
    puts BAR
  end
end

class FooChild < Foo
  BAR = 'Child'
end

Foo.speak # Parent
FooChild.speak # Parent

虽然类实例变量依赖于self

的值
class Foo
  @bar = 'Parent'

  def self.speak
    puts @bar
  end
end

class FooChild < Foo
  @bar = 'Child'
end

Foo.speak # Parent
FooChild.speak # Child

如果使用self的显式引用,则可以获得与常量相同的行为:

class Foo
  BAR = 'Parent'

  def self.speak
    puts self::BAR
  end
end

class FooChild < Foo
  BAR = 'Child'
end

Foo.speak # Parent
FooChild.speak # Child