Uninitialized variables

Posted by Sergey Enin 31 July 2011 at 04:37

In comment to one of previous posts wrote how usually ruby developers solve uninitliazed variables problem in conditions:

if (!!@a)

This works, cause:

1) in Ruby, everything evaluated as TRUE, but not FALSE or NIL!

2)  > !nil
 => true
#so, !!nil => false;

3) in Ruby uninitialized instance variables evaluated as nil;

 

I dont believe it is best way(though possible). Consider, that if you are cared programmer and develop with "ruby -w" ruby will write you warning.

 

However, I decided to review uninitialized variables in ruby:

 

@@a - Class variables:

ruby-1.9.2-p136 :004 > @@a
NameError: uninitialized class variable @@a in Object

 

@a - Instance variables:

ruby-1.9.2-p136 :003 > @a
 => nil

(if -w - then cause warning)


$a - Global variables:

ruby-1.9.2-p136 :011 > $a
 => nil

(if -w - then cause warning)

 

a - Local variables:

ruby-1.9.2-p136 :001 > a
NameError: undefined local variable or method `a' for main:Object

but

if we will do

ruby-1.9.2-p136 :003 > a = 2 if false
 => nil
ruby-1.9.2-p136 :004 > a
 => nil


A - Constants:

ruby-1.9.2-p136 :002 > A
NameError: uninitialized constant Object::A

 

Thank you.

Links:

Posted in ,  | Tags , , ,