Ruby On Rails入门经典 第三章 类和对象
来源:
作者:
时间:2007-11-07
Tag:
点击:
创建模块:
使用module关键字
module Sentence
def Sentence.add(word_one, word_two)
return word_one + " " + word_two
end
end
def Sentence.add(word_one, word_two)
return word_one + " " + word_two
end
end
使用模块:
require 'sentence'
puts "2 + 3 = " + Sentence.add(2, 3).to_s
不能使用模块创建实例
require 'sentence' 相当于 include 'sentence.rb'
模块中还可以包含类:
module Mathematics
class Adder
def Adder.add(operand_one, operand_two)
return operand_one + operand_two
end
end
end
混和插入:
可以把模块中的方法包含到类中
module Adder
def add(operand_one, operand_two)
return operand_one + operand_two
end
end
module Subtracter
def subtract(operand_one, operand_two)
return operand_one - operand_two
end
end
class Calculator
include Adder
include Subtracter
end
calculator = Caculator.new()
0
