The below code works. Question though. How does add_to_stack acess the @stack instance variable going through the method stack? In this case
is stack variable looked at as literally the array?
Okay. Let me try and further explain. With stack.push(obj) I would
understand if it said @stack.push(obj) but that actually breaks the
code. In the add_to_stack method.
On Sat, Jul 13, 2013 at 9:55 PM, Michael W. [email protected]
wrote:
Okay. Let me try and further explain. With stack.push(obj) I would
understand if it said @stack.push(obj) but that actually breaks the
code. In the add_to_stack method.
On Sat, Jul 13, 2013 at 9:55 AM, Michael W. [email protected]
wrote:
Okay. Let me try and further explain. With stack.push(obj) I would
understand if it said @stack.push(obj) but that actually breaks the
code. In the add_to_stack method.
This is because the stack method will initialize the @stack instance
variable if it doesn’t already exist:
The ||= operator is common in ruby code. In this case, it will
initialize
the @stack instance variable to a new array if it hasn’t yet been
initialized. Search the forum for the gritty details on how ||= works
and
how it can be interpreted. It is pretty complicated under the covers.
If you try to just access @stack in the add_to_stack method, your code
will
break because the @stack instance variable has not been initialized.
But
accessing it through the stack method makes sure it gets initialized
when
it is needed.
Okay. Let me try and further explain. With stack.push(obj) I would
understand if it said @stack.push(obj) but that actually breaks the
code. In the add_to_stack method.
Douglas already explained why.
To elaborate further: the following would work,
but I would prefer your original code: