Ruby LanguageVariable Scope and Visibility


Syntax

  • $global_variable
  • @@class_variable
  • @instance_variable
  • local_variable

Remarks

Class variables are shared in the class hierarchy. This can result in surprising behavior.

class A
  @@variable = :x

  def self.variable
    @@variable
  end
end

class B < A
  @@variable = :y
end

A.variable  # :y

Classes are objects, so instance variables can be used to provide state that is specific to each class.

class A
  @variable = :x

  def self.variable
    @variable
  end
end

class B < A
  @variable = :y
end

A.variable  # :x