Quantcast
Channel: SitePoint » Darko Gjorgjievski
Viewing all articles
Browse latest Browse all 7

Understanding Scope in Ruby

$
0
0

Scope is an essential thing to understand, not just in Ruby, but in any programming language. Back in the days when I was starting to write Ruby, more than half of the errors thrown at me were as a result of not understanding this concept well enough. Things like variables not being defined, incorrect variable assignments, and so on. All as a result of not understanding scope well enough. You don't have to go through all of these headaches! This article will hopefully help you avoid many of the mistakes I did.

What is Scope, Exactly?

When someone mentions scope, think of 2 words: variables and visibility.. It's pretty straightforward: Scope is all about where something is visible. It's all about what (variables, constants, methods) is available to you at a given moment. If you understand scope well enough, you should be able to point at any line of your Ruby program and tell which variables are available in that context, and more importantly, which ones are not.

So what's the point of restricting visibility to variables in the first place? Why not have everything available anywhere? Life would be much easier that way, wouldn't it? Well, not really...

There are many things programmers disagree about (using a functional vs. object-oriented approach, using different variable naming templates, etc.). Scope is not one of them. Especially as people get more experience with programming, they are stronger proponents of it. Why is that?

Because the more you work in programming, the more you'll have the chance to experience the horror of having everything available everywhere. Global state makes your program very unpredictable. It's very hard to track who changes what when everyone has the ability to do so. Who wrote to this variable? Who read it? Imagine having ten thousand lines of code and asking these questions for each line!

Then come naming issues. If you have a big program, you'd have to give all of your variables unique names to avoid conflicts. Imagine keeping track of thousands of variable names.

Continue reading %Understanding Scope in Ruby%


Viewing all articles
Browse latest Browse all 7

Latest Images

Trending Articles



Latest Images