oclockvn
3/21/2019 - 4:08 PM

Ruby scope

Ruby scope

class Scope

#starts with $
$global_scope = "/app" #available anywhere

#starts with @@
@@same_class_scope = 1 #available across class instances

def local_scope
  #local variable starts with lowercase or underscore _
  loval_var = 10 #only available to this method
end

def class_scope
  #class variable starts with @
  @name = 'Ruby' #available to this class
end

def set_scope(num)
  @@same_class_scope = num
end

def print_scope
  puts @@same_class_scope
end

end

s1 = Scope.new
s2 = Scope.new

s1.print_scope #=> 1
s2.set_scope(2) #all instances of Scope class will update scope

s1.print_scope #=> 2
s2.print_scope #=> 2