Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ruby Variable Scopes

Miha Rekar
January 20, 2015

Ruby Variable Scopes

Miha Rekar

January 20, 2015
Tweet

More Decks by Miha Rekar

Other Decks in Programming

Transcript

  1. SCOPES • Local Variables • Instance Variables • Class Variables

    • Class Instance Variables • Global Variables • Constants
  2. LOCAL VARIABLES • “normal” • x = 25 • local

    to a method/block/class declaration • goes away when its scope closes
  3. INSTANCE VARIABLES • prefixed with `@` • @name = ‘Miha’

    • available inside an instance scope • each instance has a separate value
  4. CLASS VARIABLES • prefixed with `@@` • @@gears = 5

    • available inside a class and instance scope • same for all instances • same for superclass and subclasses
  5. CLASS VARIABLES EXAMPLE class Polygon @@sides = 10 def self.sides

    @@sides end end puts Polygon.sides # => 10 class Triangle < Polygon @@sides = 3 end puts Triangle.sides # => 3 puts Polygon.sides # => 3
  6. CLASS INSTANCE VARIABLES • classes are objects too • prefixed

    with `@` • @cards = 52 • available anywhere inside a class scope • NOT same for superclass and subclasses
  7. CLASS INSTANCE VARIABLES EXAMPLE class Polygon @sides = 8 def

    self.sides @sides end def sides @sides end end puts Polygon.sides # => 8 puts Polygon.new.sides # => nil class Triangle < Polygon @sides = 3 end puts Triangle.sides # => 3 puts Polygon.sides # => 8
  8. GLOBAL VARIABLES • prefixed with `$` • $HOME = ‘Ljubljana’

    • should be used sparingly • available everywhere • can be traced
  9. CONSTANTS • begin with a capital letter • upper snake

    case by convention • I_AM_A_CONSTANT = 25 • supposed to remain constant
  10. CONSTANTS EXAMPLE [1] pry(main)> A_CONST = 10 => 10 [2]

    pry(main)> A_CONST = 20 (pry):50: warning: already initialized constant A_CONST (pry):49: warning: previous definition of A_CONST was here => 20 [3] pry(main)> A_CONST => 20