Hidden Instance Variables
In this chapter, you will learn about inspecting an object, customizing the inspect message and visibility of instance variables.
Inspecting an Object
We can print the car object to inspect it.
class Car
def initialize(color)
@color = color
end
def drive
'driving'
end
end
car = Car.new('red')
p car
This prints:
#<Car:0xcafb @color="red">
This shows that the car instance has the color instance variable with the value red and the memory location #CAFB
of the car object.
Customize Inspecting an Object
We can provide a custom implementation of to_s method.
class Car
def initialize(color)
@color = color
end
def drive
'driving'
end
def to_s
"I am a #{@color} car"
end
end
car = Car.new('red')
puts car
The to_s provides string representation of the car object. This prints:
I am a red car
Visibility of Instance Variable
The instance variables are not visible from the outside of an object.
Let's see what happens when we access the color instance variable.
class Car
def initialize(color)
@color = color
end
def drive
'driving'
end
end
car = Car.new('red')
p car.color
This gives an error:
NoMethodError: undefined method ‘color’ for #<Car:0x007fbc0 @color="red">
We can define a color method that returns the color instance variable.
class Car
def initialize(color)
@color = color
end
def color
@color
end
end
car = Car.new('red')
p car.color
This prints:
red
Ruby has accessors that expose variables to the outside. So, instead of defining our own method, we can use attr_reader.
class Car
attr_reader :color
def initialize(color)
@color = color
end
end
car = Car.new('red')
p car.color
This prints:
red
- By default, instance variables are hidden from the outside.
- We can expose an instance variable via an accessor.
- You can over-ride the to_s method to customize the inspect message.
Summary
In this chapter, we inspected the color instance variable of the car object. We also discussed the concept of accessing the instance variables via accessors.