Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using remove_instance_variable vs. set to nil

Tags:

ruby

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?

like image 774
User314159 Avatar asked Mar 25 '14 01:03

User314159


1 Answers

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 > 
like image 65
tompave Avatar answered Nov 06 '22 20:11

tompave