From: Stefano Crocco Date: 2009-11-24T16:47:33+09:00 Subject: Re: Warning: instance variable @foo not initialized On Tuesday 24 November 2009, Seebs wrote: > |Running some simple tests with Prawn, I am getting thousands of lines > |of warnings from Ruby 1.9.1: > | > |/usr/local/lib/ruby/gems/1.9.1/gems/prawn-layout-0.3.2/lib/prawn/table/cel > |l.rb:255: warning: instance variable @text_color not initialized > | > |There are hundreds of these, and they seem to come from a lot of usages > |like: > | > |e.text_color ||= @text_color > | > |or this kind of usage: > | > | def page_content > | @active_stamp_stream || @store[@page_content] > | end > | > |In the latter case, @store is apparently fine, it's just > | @active_stamp_screen which is uninitialized. > | > |Should I infer that the library should be setting these all to nil in its > |initialize()? > | > |-s > | When an instance variable is referred to before a value has been assigned to it, it automatically gets the value nil and the warning you see is emitted. The reason for the warning, I guess, is to help finding situations where you make a mistake writing the name of the variable. For example, in the following code @var = 4 if @vra < 5 ... @vra in the second line should obviously have been @var. Without the varning, it would have been easy to overlook this mistake (expecially if the variable name was longer than only three characters). The warning helps spotting it. To answer your question: the library should have set those variable to nil before using them, if it wanted to avoid the warning (not necessarily in initialize, just before the variables were used). Not doing so, however, is perfectly correct, if you don't mind seeing the warnings. Personally, I don't like them, so I always assign instance variables before using them. I hope this helps Stefano