Modules and mixins in Ruby
Sharing behavior across classes without inheritance.
# a module holds behavior; include mixes it into any class
module Greetable
def greet
"hi, I am #{display_name}"
end
end
class Robot
include Greetable
def initialize(id)
@id = id
end
def display_name
"unit-#{@id}"
end
end
puts Robot.new(7).greet
How it works
- A module defines methods with no class of their own.
includemixes the module into a class as instance methods.- The mixin calls
display_name, which the host class provides.
Keywords and builtins used here
Robotclassdefdisplay_nameendgreetidinitializemoduleputs
The run, in numbers
- Lines
- 20
- Characters to type
- 249
- Tokens
- 45
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 32 seconds.
Step 3 of 3 in Classes & modules, step 21 of 29 in Language basics.