Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Why is an instance variable defined inside a class nil?

Tags:

ruby

class Something
  @b = [4432]
  def screen
    puts @b.class
  end
end
s = Something.new
s.screen

outputs 'Nilclass'. Was wondering, why does an instance variable which is defined inside a class always part of NilClass?

like image 510
daremkd Avatar asked Oct 09 '13 10:10

daremkd


3 Answers

Instance variables belong to an object (aka an instance), that's why they are called instance variables. Every instance has its own instance variables.

In your case, there are two objects: Something (which is an instance of Class) and s (which is an instance of Something). Each of those two objects has its own set of instance variables. Something has an instance variable called @b which points to [4432]. s has no instance variable named @b because you never assign to it, and uninitialized instance variables evaluate to nil.

like image 105
Jörg W Mittag Avatar answered Sep 28 '22 11:09

Jörg W Mittag


You need to set it like this:

class Something
  def initialize
    @b = [4432]
  end

  def screen
    puts @b.class
  end
end

The way you did it, the variable belongs to Something class itself, not its instance. Observe:

class Something
  @b = [4432]
end


s = Something.new
s.instance_variable_get(:@b) # => nil # !> instance variable @b not initialized

Something.instance_variable_get(:@b) # => [4432]
like image 33
Sergio Tulentsev Avatar answered Sep 28 '22 13:09

Sergio Tulentsev


Generally the instance variable must be defined inside the constructor whereas in ruby the default constructor is initialize the syntax is

def initialize

end #these is the default constructor in ruby so when we define the insatnce variable inside the constructor and when we create the instance of a class then that instance/object will contain the copy of instance variables

most important thing is that though the instance/object contains the instance variable the instance/object cannot access it why because by default the instance data is private so in order to access it we need to define the getters and setter for those instance variable

class Something    
attr_accessor:b
def initialize
@b = [4432]
end
s=Something.new
puts"#{s.b}"
like image 44
khan Avatar answered Sep 28 '22 12:09

khan