Skip to content

Instantly share code, notes, and snippets.

@chensoren
Created June 19, 2013 14:20
Show Gist options
  • Save chensoren/5814684 to your computer and use it in GitHub Desktop.
Save chensoren/5814684 to your computer and use it in GitHub Desktop.
ruby module extend and include
module Stringify
# When a class includes a module
# the module’s self.included method will be invoked.
def self.included(base)
# Initialize module.
end
# Requires an instance variable @value
def stringify
if @value == 1
"One"
elsif @value == 2
"Two"
elsif @value == 3
"Three"
end
end
end
module Math
# When a class extends a module
# the module’s self.extended method will be invoked
def self.extended(base)
# Initialize module.
end
# Could be called as a class, static, method
def add(val_one, val_two)
BigInteger.new(val_one + val_two)
end
end
class Number
def intValue
@value
end
end
# BigInteger extends Number
class BigInteger < Number
# Add instance methods from Stringify
include Stringify
# Add class methods from Math
extend Math
# Add a constructor with one parameter
def initialize(value)
@value = value
end
end
# Create a new object
bigint1 = BigInteger.new(10)
# Call a method inherited from the base class
puts bigint1.intValue # --> 10
# Call class method extended from Math
bigint2 = BigInteger.add(-2, 4)
puts bigint2.intValue # --> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment