Ruby Language Variable Scope and Visibility

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?