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?
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
.
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]
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With