Programming Diary 11.10.16

I have been reviewing variable scope today. Here are my notes from today:

Inner scope can access variable initilalized in an outer scope, but not vice versa.

Methods create their own scope that is entirely outside the execution flow. We can pass in Variables by including them as parameters, and we can create variable inside the mthod. But we cannot simply access variable without passing them in and we cannot access variable created inside the method outside of it.

Do not mix up do/end with methods when you’re working with variable scope issues.

When we use ‘each’, ‘times’ and other methods, followed by ‘{}’ or ‘do/end’, that’s when a new block is created.

We can create a var in the outer scope. Access it with times, change it and then print it out in the outer scope:
a = 7 # create the var
3.times do |n|
 a = 16 # reassign it
end
puts a # puts out 16
The above code works because we are only reassigning the variable and not creating it.

This would not work: 
3.times do |n|
 a = 16 # initialize the variable inside a block
end
puts a # puts out method error / a not found.

This gives us a ‘no method error’ because the var was initialized inside a block and we cannot access that outside.

When you place a ‘return’ in the middle of a method, it just return the evaluated results, without executing the next line. If we don’t use ‘return’, the last line of a method is the return value.

The return value is precede by the “=>”.

Flow-control

If x = 5
 Puts “how can this be true?”
Else
 Puts “it is not true”
End
The code above will always put out the first statement because assigning a variable is always going to be true.

Loops

We can exit a loop with ‘break’.
With ‘next’ we can skip to the next iteration of the loop.