On Tue, Jan 25, 2011 at 11:53 PM, Peter Vandenabeele
<peter / vandenabeele.com> wrote:
> Robert Klemme wrote in post #977145:
>> On Mon, Jan 24, 2011 at 3:22 PM, Jon Leighton <j / jonathanleighton.com>
>> wrote:
> ...
>>> and even:
>>>
>>> if false
>>> foo =3D 1
>>> bar =3D 2
>>> end
>>>
>>> (results in both foo and bar being assigned nil)
>>
>> This is not exactly true: foo is not "assigned nil" but rather is foo
>> initialized as a local variable and initially a variable refers nil.
>> There is no assignment but because you have an assignment in code
>> (even though it's no executed) the local variable comes into existence
>> (see above).
>
> To understand this better, I used the method 'defined?'.
> Would 'defined?' be a correct way to determine if a name was
> already 'initialized as a local variable' in this case?

You can certainly do that for learning purposes but I have not yet had
the need to use defined? in a real program.

> $ rvm use 1.9.2 =A0# (same behavior in 1.8.7)
> Using /home/peterv/.rvm/gems/ruby-1.9.2-p136
> $ irb
> 001:0> defined?(x) =A0#=3D> nil
> 002:0> if false
> 003:1> x =3D 10
> 004:1> end =A0#=3D> nil
> 005:0> defined?(x) =A0#=3D> "local-variable"
> 006:0> x =A0#=3D> nil

IRB cannot be trusted on things like this as it has different behavior
for local variables than the Ruby interpreter.  Better do something
like this:

09:10:10 ~$ ruby19 <<CODE
> def f
> p defined?(x)
> if false
> x=3D10
> end
> p defined?(x)
> end
> f
> CODE
nil
"local-variable"
09:11:06 ~$

Kind regards

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/