CMSC330

Modules

Modules

Modules
Common Modules

Modules

Modules

Recall inheritance


class A
  def to_s
    "I am A"
  end
end

class B < A
  def to_s
    super() + " and I am B"
  end
end
          

Issue: can only have one parent

Workaround: modules

Workaround: modules

A Module is a collection of methods and constants


# double-module.rb
module Doubler 
  def Doubler.base
    2
  end

  def double
    self + self
  end
end

# things we can do
puts Doubler.base
puts Doubler.class
puts Doubler.instance_methods

# things we cannot do
puts Doubler.new
puts Doubler.double
          

How to use Module?


# triple-module.rb
module Triple 
  def triple 
    self + self + self
  end
end

class Integer
  include Triple
end
          

puts 10.triple
          

Consider the following


module M1
  def bye
      "So long"
  end
end

module M2
  def bye
      "Goodbye"
  end
end

class C
  include M1
  include M2

  def bye 
    "C you later"
  end
end
          

What happens?


sea = C.new
puts sea.bye
          

What if we change some things


class C
  include M1
  include M2
end

# get rid of C's bye
c = C.new
puts c.bye

class C
  include M2
  include M1
end

# get rid of C's bye and swap order
c = C.new
puts c.bye

# consider
c.class.ancestors

class A
  def to_s
    "A"
  end
end

class B < A
  include M1
  
  def to_s
    "B"
  end
end

puts B.new.class.ancestors
          

Common Modules

Common Modules you may see or need to include


class Name
  attr_accessor :first
  include Comparable
  def <=>(other) #need to overwrite this
    if @first > other.first 
      1
    elsif @first < other.first 
      -1 
    else
      0
    end
  end

class Class
  attr_accessor :roster
  include Enumerable

  def each # need to overwrite this
    for person in roster
      yield person
    end
  end
end