pixatlazaki
pixatlazaki

Reputation: 561

What is the difference between class constants and class instance variables in Ruby?

I will note that there are a lot of similarly worded questions that are distinct from what I believe I'm asking.

What is the difference between the following in terms of functionality? E.g. how do they behave with regards to inheritance?

class Foo
  BAR = 'Hello'
end

and

class Foo
  @bar = 'Hello'
end

Upvotes: 1

Views: 71

Answers (1)

pixatlazaki
pixatlazaki

Reputation: 561

Access

Constants are public by default (we're disregarding private constants here). Class instance variables are not accessible (except with stuff like Object#instance_variable_get, but that's typically not very good style) without a reader and/or writer method.

Inheritance

Constants will refer to the value in the context in which they are used, not the current value of self. For example,

class Foo
  BAR = 'Parent'

  def self.speak
    puts BAR
  end
end

class FooChild < Foo
  BAR = 'Child'
end

Foo.speak # Parent
FooChild.speak # Parent

While class instance variables are dependent on the value of self:

class Foo
  @bar = 'Parent'

  def self.speak
    puts @bar
  end
end

class FooChild < Foo
  @bar = 'Child'
end

Foo.speak # Parent
FooChild.speak # Child

If you use an explicit reference to self, you can get the same behavior as constants, however:

class Foo
  BAR = 'Parent'

  def self.speak
    puts self::BAR
  end
end

class FooChild < Foo
  BAR = 'Child'
end

Foo.speak # Parent
FooChild.speak # Child

Upvotes: 5

Related Questions