Using remove_instance_variable vs. set to nil

ruby

Solution

Setting a variable to `nil` preserves the variable, intended as a container, but changes the contained value to `nil`.

Removing a variable, well, removes it.

In the case of instance variables it doesn't change much, at least in your example. The reason is that accessing an undefined `@instance` variable will return `nil`, as that is the expected behavior of Ruby:

$ irb
2.1.0 :001 > var
NameError: undefined local variable or method `var' for main:Object
    from (irb):1
    from /Users/Tom/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
2.1.0 :002 > @var
 => nil 
2.1.0 :003 > 

However, this similarity is limited to the outcome of read operations. In fact, removing a variable is not the same thing as setting it to nil:

$ irb
2.1.0 :001 > 
2.1.0 :002 >   defined? @var
 => nil 
2.1.0 :003 > @var = nil
 => nil 
2.1.0 :004 > defined? @var
 => "instance-variable" 
2.1.0 :005 > 

Problem

Consider this ``` class SomeClass attr_reader :var def initialize @var = 42 end def delete_var remove_instance_variable(:@var) end def delete_var_2 @var = nil end end ``` What is the difference between delete_var and delete_var_2?

Original source