Methods Flashcards
What are methods and why do we need them?
A piece of code that needs to be executed many times in a program
What must we do before we can use a method?
Define it using the reserved word [def], name it and use [end] to complete
How do we invoke a method?
By typing it’s name and passing it in arguments
When would you use a parameter?
When you have data outside of a method definition’s scope, but you need to access it within a method’s definition
What is an argument?
Pieces of information that are sent to a method invocation to be modified or used to return a specific result
When do we pass arguments to a method?
When we call the method
What is the benefit of a method?
Gives us the ability to make changes in one place that affect many places in our program
What is the purpose of a default parameter?
So that the method always works whether it is given an argument or not
Where does a method definition create its scope?
Outside the regular flow of execution
How do you call a method?
Either the some_method(obj) call or a_caller.some_method(obj) call
Can methods be altered permanently outside of the definition?
Yes, by mutating the caller
True or False: Ruby methods always returns the evaluated result of the last line of the expression unless an explicit return comes before it
True
How do we explicitly return a value?
By using the keyword [return]
Is the reserved word [return] required in order to return something from a method?
No
Why are we able to chain methods together?
Because every method call returns a value
If a method returns the value “nil” will we be able to chain methods?
No. Because “nil” doesn’t know how to respond to further calls
True or false: we can pass method call as an argument
True
What does the call stack do?
Helps your programming language keep track of what method is executing as well as where execution should resume when it returns
Aside from methods, what else uses the call stack?
Blocks, procs and lambdas
True or false: all Ruby methods (including built in ones like [puts]), share the same call stack
True
When does a stack frame get popped from the call stack?
When a method returns a value
When does a program end?
When the main method has no more code to run and gets popped from the call stack