Variables Flashcards
Variable Scope
Determines where in a program a variable is available for use. Is defined by where the variable is initialized or created. Is defined by a method definition or a block
Rule one of variable scope
Inner scope can access variables initialized in an outer scope, but not vice versa.
Variables
used to store information to be referenced and manipulated in a computer program
assignment operator
= (assigns value)
equality operator
== (checks if two things are equal)
block
piece of code that follows a method’s invocation, delimited by either curly braces {} or do/end
scope.rb
a = 5 # variable is initialized in the outer scope
3.times do |n| # method invocation with a block
a = 3 # is a accessible here, in an inner scope?
end
puts a
What is the value of a when it is printed to the screen?
The value of a is 3. This is because a is available to the inner scope created by 3.times do … end, which allowed the code to re-assign the value of a.
Convert the following code into a one liner: # scope.rb
a = 5 # variable is initialized in the outer scope
3.times do |n| # method invocation with a block
a = 3
end
puts a
3.times { |n| a = 3 }
Constants
- declared by capitalizing every letter in the variable’s name.
- used for storing data that never needs to change
Global Variables
declared by starting the variable name with the dollar sign ($).
-these variables are available throughout your entire app, overriding all scope boundaries.
Class variables
declared by starting the variable name with two @@ signs. -accessible by instances of class as well as the class itself.
Instance variables
- declared by starting the variable name with one @ sign.
- available throughout the current instance of the parent class.