Variables Flashcards
What is a variable?
A way to store information to be referenced and manipulated in a computer program
What do variables do?
Provide a way of labelling data with a descriptive name
What is the sole purpose of a variable?
To label and store data in memory
When naming a variable, what is considered good practice?
Making sure the name assigned to the variable is accurately descriptive and understandable to the reader
How would we get rid of the newline at the end of a string?
Add .chomp to the end of that string
What does a newline character represent?
Hitting the enter key
What does a variable’s scope determine?
Where in a program a variable is available for use
How is a variable’s scope defined?
A variable’s scope is defined by where the variable is initialized or created
How is a variable’s scope defined in Ruby?
By a method definition or a block
What is a method?
A piece of reusable code that your program can execute many times during its run
What does ‘methods have self contained scope’ mean?
Means only variables initialized within the method’s body can be referenced or modified within the method’s body
Are variables initialized within a method’s body available outside of it?
No
What is a block?
A piece of code that follows a method’s invocation, delimited by either curly braces or do/end
What is one rule we need to emphasize with blocks?
Inner scope can access variables initialized in an outer space, but not vice versa
How do we know if curly braces or do/end delimiting code is a block?
By seeing if they immediately follow a method invocation. If they do, it is a block
What are the 5 types of variables?
- Constants
- Global variables
- Class variables
- Instance variables
- Local variables
How are constants declared?
By capitalizing every letter in the variable’s name
What are constants used for?
For storing data that never needs to change
Can you change the value of a constant?
In most coding languages - no. In Ruby, yes.
Can constants be declared in method definitions?
No. They are available throughout your application’s scopes
How are global variables declared?
By starting the variable name with a $ (dollar sign)
Where are global variables available?
Throughout your entire app, overriding all scope boundaries
How do you declare a class variable?
By starting the variable name with @@
Where are class variables accessible?
They are available by instances of your class, as well as the class itself