Ruby Intro/Variables Flashcards
what is a variable?
what are its two parts?
“a container that holds info”/”a way to label data with a descriptive name”/”a variable’s purpose is to name and store data in memory”
a name and a value
x = true
(x is the name, true is the value)
*choose a variable’s name carefully. make sure it’s descriptive and easily understood by you and other programmers)
irb :001 > a = 4 => 4 irb :002 > b = a => 4 irb :003 > a = 7 => 7 ---------------- What is the value of b now?
It’s still 4 because what was the value of “a” when you linked “b” to it
“variables point to value in memory”
What does the “gets” method do?
It allows the user to input data/It gets a sting from a user
“gets” pauses the program and waits for the user to type in some information and hit the enter key
What does “chomp” do?
it removes the newline character ( \n ) that automatically appears at the end of a string when “gets” is used
What is a block?
a piece of code that follows a method’s invocation
You can use { } if all the code fits on one line:
total = 0
[1, 2, 3].each { |number| total += number }
puts total
OR……
“do/end” if the code takes up two or more lines:
total = 0 [1, 2, 3].each do |number| total += number end puts total
If you see some code in ruby, how do you know if it’s a block?
the code follows the invocation of a method
( .times, .split, etc)
This is NOT a block:
for i in arr do
a = 5
end
puts a
Why? the “do/end” part doesn’t follow the invocation of a method. also, “a” is accessible in the program b/c “a=5” was not created in the inner scope of a block. in other words, no “inner scope” was created
True or false?
Variables set inside of a block or a method are accessible outside of that block or method?
false
True or false?
Code created in a block or method can access a variable initialized outside of that block or method.
true
Is this a block? Why or why not?
3.times { |n| a = 3 }
yes, because the code inside { } follows the invocation of a method (.times)
What are the five types of variables? 1- c\_\_\_\_\_\_ts 2- g\_\_\_\_\_\_l variables 3- c\_\_\_\_\_s variables 4- i\_\_\_\_\_\_e variables 5- l\_\_\_\_\_\_l variables
Which type is the most common
constants (named in ALL_CAPS)
global variables (name starts with $. not used very often)
class variables (name starts with @@ )
instance variable (name starts with @ )
local variables (named with snake_case ) -----------
local variables are the most commonly used in ruby
What does this mean?
x += 1
It’s shorthand for “x = x + 1”
this math operation is called “reassignment”
Are there any problems here?
y = 0 3.times do y += 1 x = y end puts x
Yes.
x was initialized inside the block, so it is not visible to the outer scope
(inner scope vs. outer scope)