It’s how Ruby was designed.
Classes can be subclasses to one another to incorporate code in the parent class, where as modules by the interpreter are super classes. Any data inside a module can be shared by any class. On top of that, data in modules can be used by any programs that require or load the module.
For regular classes, they cannot pull data from each other without aliasing them.
class Animal
attr_accessor :name , :type , :age
end
Class Cat
end
In order for the Cat class to use the data from the Animal class, you need to alias(or link them) together.
class Cat > Animal
end
smokey = Cat.new
smokey.name = “Smokey”
smokey.type = “feline”
smokey.age = 2
You will have to do this for every new class you make that uses the data from the Animal class. This is where modules come to play. By making the Animal class into a module,. Any new class can use the Animal data.
module Animal
attr_accessor :name , :type , :age
end
The Cat class will now look like this.
class Cat
Include Animal
end
honey = Cat.new
honey.name = “Honey”
Ruby is built for “only code once”. You don’t want to have to recode something from another class for every new class. Modules help this process. Becuase now you have a super class you can include into all new classes which has its own attributes and variants. Now we can expand the Cat class.
class Cat
include Animal
attr_accessor :breed , :tailed, :tailess
end
And a new Dog class.
class Dog
include Animal
attr_accessor :pedigree , :stature, :woof
end