Damián M. González wrote in post #1109021:
Hi guys. Can you tell me why does this happen?
if 1.==(2)
c = 3
else
b = 5
end
defined?(c)
#=> "local-variable"
I was expecting nil, because the thread doesn't pass trough the second
line, 1 is not equal to 2. Seems that Ruby gives the value nil to c, so
Ruby creates the object in RAM, will be garbage collected after, of
course. Why does this happen? it is not a waste of resources?
I may be wrong, but I think it being a "local-variable" means the token
'c' is known by the parser to refer to an entry in the "local variables"
table, and not, for example, in the "functions" table. This is directly
related to the following, which crops up from time to time:
def c() 'function c() called'; end
c if c = 1
#=> "function c() called"
c
#=> 1
The parser reads the source left-to-right, top-to-bottom, including the
bits that aren't necessarily executed at runtime, and builds its
knowledge of the tokens based on that read-through. When it sees an
assignment to 'c', even if it's inside a never-executed if-block, it
knows that _from that point on_ 'c' is a local variable. Any
invocations of 'c' that occur before the assignment will have
necessarily been interpreted according to what the parser knew _at the
time it was parsed_. (I.e. above it knew 'c' was a function, even though
in execution order the assignment happens first.)
Note that in your original code no objects have been created, because
without the assignment being _executed_, the 'c' entry in the local
variables table refers to the 'nil' singleton object, which already (and
always) exists:
if 1.==(2)
c = 3
else
b = 5
end
#=> 5
defined?(c)
#=> "local-variable"
c
#=> nil
···
--
Posted via http://www.ruby-forum.com/\.