Ruby Variable Scopes

Ruby Variable Scopes

5a5fcbae333f071dc7a28f4958509db5?s=128

Miha Rekar

January 20, 2015
Tweet

Transcript

  1. RUBY VARIABLE SCOPES

  2. SCOPES • Local Variables • Instance Variables • Class Variables

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

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

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

    • available inside a class and instance scope • same for all instances • same for superclass and subclasses
  6. 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
  7. CLASS INSTANCE VARIABLES • classes are objects too • prefixed

    with `@` • @cards = 52 • available anywhere inside a class scope • NOT same for superclass and subclasses
  8. 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
  9. GLOBAL VARIABLES • prefixed with `$` • $HOME = ‘Ljubljana’

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

    case by convention • I_AM_A_CONSTANT = 25 • supposed to remain constant
  11. 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
  12. THANKS