Wednesday, March 30, 2011

Scope and Rookie Mistakes (My first ruby program p.4)

Scope
Imagine a master clock-maker. He sits on a specialized wooden desk surrounded by empty bins on which he puts the parts of clocks he makes or repairs. Behind him is the eager young assistant. The assistant is great and helpful and will look for any tool the master needs, so the master can concentrate. And concentrate he will. He puts on his magnifying glasses, and starts to work. The assistant not only fetches tools but also clears up bins around the master that he is not using. The assistant knows one key thing about the master. He can only focus on one object at once. If he's working on a gear that's all he knows. If he's working on a mechanism that's all he knows.  His magnifying glasses obscure the vision around him so he won't notice something next to him if it's not in his field of view. That's kind of how Ruby works. The field of view at any time is the scope. When the master puts what's his working down and says he's done the assistant swoops in and takes that stuff away.



On my first program I immediately made a mistake on scope that I sort of stumbled to solving but now I know why what I did worked. When I ran the original program I ran into an error: undefined local variable or method 'text'.
"Hmm not defined?" I thought; so I went ahead and added this line to the top text = Object.new to define it. But this is unnecessary. The problem I was running into was that I had put a puts statement after I told the assistant I was done. The assistant came by and removed the text variable I had just created. Then after it was cleared, I wanted to access it again with puts. The master clock maker looks around sees no text variable and spits out an error.

"What text? What is this text? You kids and your texting..." he says.

This also meant that I only displayed text after the loop had finished and so probably would only show one file (the last one) instead of all. As you see once I put the puts text back into the block (do..end) it works, even without the text = Object.new line.

No comments:

Post a Comment