The extend method will mix a module’s methods at the class level.
On the other hand, the include method will mix a module’s methods at the instance level, meaning the methods will become instance methods of the class.
module Stringify
# Requires an instance variable @value
def stringify
if @value == 1
"One"
elsif @value == 2
"Two"
elsif @value == 3
"Three"
end
end
end
module Math
# Could be called as a class, static, method
def add(val_one, val_two)
BigInteger.new(val_one + val_two)
end
end
# Base Number class
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
bigint1 = BigInteger.new(10)
puts bigint1.intValue # 10
bigint2 = BigInteger.add(-2, 4)
puts bigint2.intValue # 2
puts bigint2.stringify # "Two"
Posted by Sandheep to Sandheep's deck (2013-04-26 05:56)