# Instance variable not initialized warning

**URL:** <https://www.ruby-forum.com/t/instance-variable-not-initialized-warning/72848>\
**Category:** Ruby\
**Created:** [October 19, 2006, 11:37am UTC](https://www.ruby-forum.com/t/instance-variable-not-initialized-warning/72848 "2006-10-19T11:37:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Esad\_H](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/3da27b/32.png) [@Esad\_H](https://www.ruby-forum.com/u/Esad_H)\
**Post date:** [October 19, 2006, 11:37am UTC](https://www.ruby-forum.com/t/instance-variable-not-initialized-warning/72848/1 "2006-10-19T11:37:12Z")

</div>

Hi!

In the following piece of code:

class Foo  
def bar  
if @var.nil?  
puts “First assignment”  
@var = 1;  
else  
@var +=1;  
end  
end  
end

Foo.new.bar

When I run ruby (1.8.4)with -d ($DEBUG=true) I get to see the following  
warning:

test.rb:3: warning: instance variable @var not initialized

Does it make sense to spit out this warning even if you are doing  
something safe such as calling Object#nil?

What do you think?

---

<div class="post-metadata">

**Author:** ![Esad\_H](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/3da27b/32.png) [@Esad\_H](https://www.ruby-forum.com/u/Esad_H)\
**Post date:** [October 19, 2006, 1:18pm UTC](https://www.ruby-forum.com/t/instance-variable-not-initialized-warning/72848/2 "2006-10-19T13:18:40Z")

</div>

> Does it make sense to spit out this warning even if you are doing  
> something safe such as calling Object#nil?
> 
> What do you think?

The interpreter does not flag methods as ‘safe’ or ‘unsafe’.

If you want to get rid of the warning, you can use

if defined? @var

or

@var ||= 0  
@var += 1

Yoann
