Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby "instance variable not initialized" warning

Tags:

ruby

In writing some "learning the language" code in ruby, as part of a linkedList implementation, I came across this warning:

In the "add" method, the head is created if it doesn't already exist, i.e.

  def add(value)
   new_node=LinkedListNode.new(value)
   if !@head
     @head=new_node
   else
     self.find {|node| node.next ==nil }.next=new_node
   end
  end

I then get the warning

.../linked_list.rb:13: warning: instance variable @head not initialized

How do I get rid of this warning? What's the idiomatic way of doing this?

like image 556
Steve B. Avatar asked Jan 20 '10 02:01

Steve B.


1 Answers

In addition to Matchu's suggestion, you can also use defined? to initialize @head lazily here without provoking the warning:

if defined? @head
  ...
else
  @head = new_node
end

The normal idiom for this sort of thing is

@head ||= new_node

which will also not provoke the warning, but in this case it seems like you need to do something if @head wasn't defined, and it's not idempotent so ||= is not going to work very well in this case. ||= also has the disadvantage of not being able to distinguish between false, nil or unset. Initializing to nil in initialize is probably the best choice.

like image 111
Logan Capaldo Avatar answered Oct 06 '22 07:10

Logan Capaldo