A local variable starts with a lowercase letter or an underscore (_). Local variables do not contain nil values like global and real variables before initialization.
Ruby> $foo
Nil
Ruby> @foo
Nil
ruby> Foo
ERR: (eval): 1:undefined local variable or method ' Foo ' for Main (Object)
The first assignment of a local variable is done much like a declaration. If you point to an uninitialized local variable, the Ruby interpreter thinks it is the name of a method; as seen above
of information.
In general, the range of local variables will be
Proc{...}
Loop{...}
Def... End
Class...end
Module...end
Entire program (unless one of the above conditions is met)
The following example, define? is an operator that checks whether an identifier has been defined. If it is defined, it returns a description of the identifier, or nil. As you can see, the bar range is
The local variable of the loop; bar is undefined when the loop exits.
Note that the starting "bar=0" cannot be omitted; This assignment allows bar ranges to be shared by P1 and P2. Otherwise p1, P2 will generate and process their own local variable bar separately, calling P2
It will also cause the "no local variables or methods" error to be defined.
The strength of process objects is that they can be passed as parameters: shared local variables are still valid even if they are passed out of the original range.
Ruby's approach to scope is pretty smart. Obviously, the contents variable in the above example is shared by reader and writer. We can also create more pairs of box-like
Reader-writer Each pair shares a contents variable and does not interfere with each other.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.