IntermediateLesson 11 of 16
Modules, Mixins & Comparable – Ruby
include, extend, prepend, namespaces as well as Enumerable and Comparable for your own classes.
A module is a collection of methods and constants that cannot be instantiated. With include you mix it into a class as a mixin – this is how you get around the lack of multiple inheritance.
module Begruessung
def begruesse
"Hello, I am #{name}"
end
end
class Person
include Begruessung
attr_reader :name
def initialize(name)
@name = name
end
end
puts Person.new("Ada").begruesse
puts Person.include?(Begruessung)
puts Person.ancestors.first(3).inspect # [Person, Begruessung, Object]Two powerful mixins of the standard library: Enumerable (you define each) and Comparable (you define <=>).
class Playlist
include Enumerable
def initialize(*titel)
@titel = titel
end
def each(&block)
@titel.each(&block)
self
end
end
pl = Playlist.new("Zebra", "Fee", "Mango")
puts pl.sort.inspect # ["Fee", "Mango", "Zebra"]
puts pl.map(&:upcase).first # ZEBRA
puts pl.include?("Mango") # true
puts pl.min_by(&:size) # Fee
puts pl.first(2).inspect # ["Zebra", "Fee"]class Version
include Comparable
attr_reader :teile
def initialize(text)
@teile = text.split(".").map(&:to_i)
end
def <=>(other)
teile <=> other.teile
end
def to_s
teile.join(".")
end
end
vs = %w[1.10.0 1.2.0 1.9.5].map { |t| Version.new(t) }
puts vs.sort.join(", ") # 1.2.0, 1.9.5, 1.10.0
puts vs.max # 1.10.0
puts Version.new("2.0") > Version.new("1.9") # true
puts Version.new("1.5").between?(vs[1], vs[0]) # trueModules also serve as namespaces. extend adds the methods as class methods, prepend places the module in front of the class – useful for wrapping methods.
module Werkzeuge
VERSION = "1.0"
def self.quadrat(x)
x * x
end
class Rechner
def summe(*z)
z.sum
end
end
end
puts Werkzeuge.quadrat(5), Werkzeuge::VERSION, Werkzeuge::Rechner.new.summe(1, 2, 3) # 25, 1.0, 6
module Laut
def sprich
super.upcase + "!"
end
end
class Katze
prepend Laut
def sprich
"meow"
end
end
puts Katze.new.sprich # MEOW!TipMethod resolution follows
ancestors: first prepended modules, then the class itself, then included modules (the most recently included first), then the parent class. When in doubt, Klasse.ancestors helps.WarningA module that is
included cannot "see" the instance variables of the class unless you document them – rather rely on methods (like name above) that the class must provide.