Directly run the Code:
Module action def jump @ distance = rand (4) + 2 puts "I jumped forward # {@ DISTANCE} feet! "Endendclass rabbit include action attr_reader: Name def initialize (name) @ name = Name endclass cricket include action attr_reader: Name def initialize (name) @ name = Name endendpeter = rabbit. new ("Peter") Jiminy = cricket. new ("Jiminy") Peter. jumpjiminy. jump ---------------------------------------------------------------------- output: I jumped forward 3 feet! I jumped forward 4 feet! Nil
Module for Ruby learning has introduced Module
When a module is used to mix some behaviors and information into a class, this behavior is called Mixin.
Mixin allows us to customize a class without rewriting this class.
The above Code uses Mixin.
The jump method is defined in the action module. The action is included in the rabbit and cricket classes, so these two classes have the jump method. Therefore, the rattit and cricket instances peter And Jiminy can call jump.
You may have discovered that Mixin gives us the multi-inheritance capability of similar classes. With the Mixin technique, we can extract many behaviors from many modules and add them to our classes.
Mixin for Ruby Learning