Using a Constructor to Configure Objects : instance variables « Class « Ruby






Using a Constructor to Configure Objects


# An instance variable is a variable that is referenced via an instance of a class
# An instance variable belongs to a given object. 
# An instance variable is prefixed by a single at sign (@)

class Animal
  def initialize(color)
    @color = color
  end

  def get_color
    return @color
  end
end

animal = Animal.new("brown")
puts "The new animal is " + animal.get_color

 








Related examples in the same category

1.In Ruby, you prefix instance variables with an at sign @
2.Print out the instance variable
3.Adding more accessors
4.class variable vs object variable