Thursday, March 15, 2007

Local Variable

Local variables are variables that hold their value only during the execution of a particular section of code. They’re called local precisely because once program execution leaves the scope where the variable was created, the variable’s name no longer has any meaning.

Local variables give you a kind of scratch-pad facility. You can use, say, the variable name x in more than one place; as long as those places have different scopes, the two x variables are treated as completely separate.

Local variables can come into being in either of two ways:
■ Through assignment: x = object
■ As an entry in the method’s argument list, initialized when the method iscalled

Variables in Ruby don’t hold object values, rather, it contains a reference to an object.

Local variables have the quality of barewords; they must start with either a lowercase letter or the underscore character (_), and they must consist entirely of letters, numbers, and underscores.
我给自己制定的命名规则是:Local variable一律用“_”开头。例如:_one_apple

Here’s how Ruby decides what it’s seeing when it encounters a bareword:
1. If there’s an equal sign (=) to the right of the bareword, it’s a local variable undergoing an assignment.
2. If the bareword is a keyword, it’s a keyword.
3. Otherwise, the bareword is assumed to be a method call.

No comments: