Afficher un message
Vieux 18/09/2007, 21h11   #8
7stud --
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Variable / Method Ambiguity

David A. Black wrote:
> No, because there's no such variable in scope. The second time through
> the loop, there's no assignment to a, and the first variable a has
> gone out of scope. So the only thing that "a" could mean, outside of
> an assignment, is the method a.
>


That doesn't seem to bear out. If you switch the if statement around so
that the assignment happens first:

def x
print "Function 'x' called\n"
99
end

for i in 1..2
if i == 1
x = 10
print "x=", x, "\n"
else
print "x=", x, "\n"
end
end


the output is:

x=10
x=10

The second time through that loop, there is no assignment to x and the
previous x has gone out of scope, yet the else clause's use of x does
not result in a method call.

As p. 329 in pickaxe2 carefully explains, it is a ruby parsing rule that
determines what x means. As I read the rule, and as Daniel explains,
and as the two examples show(the 'a' example and the 'x' example), the
rule is: if there is any code that has x=val on a line before the use of
x, then x will be interpreted as a variable. If there is no assignment
to x on a line higher in the code, then x will be interpreted as a
method call.



--
Posted via http://www.ruby-forum.com/.

  Réponse avec citation
 
Page generated in 0,05057 seconds with 9 queries