What is the difference between a Class and an Object in Ruby?
Last updated
A class is the template that defines structure and behavior; an object (instance) is a concrete thing created from that template with its own state. The class says what something can do; the object is an actual one that does it.
Class:
Defines instance methods and the shape of data (instance variables).
Created once; used to stamp out many instances.
Object:
Produced by
Class.new; each holds its own copy of instance variable values.Two objects of the same class share methods but have independent state.
Ruby twist: A class is itself an object (an instance of
Class), so the two concepts are layered, not opposed.
[lang:ruby]
class Dog # the class
def initialize(name) = @name = name
end
rex = Dog.new("Rex") # an object/instance with its own @name
fido = Dog.new("Fido") # a separate object, separate state