热门关键字:  ubuntu  分区  函数  Fedora  linux系统进程

当前位置 :| 主页>Linux教程>编程开发>Ruby>

Ruby On Rails入门经典 第三章 类和对象

来源: 作者: 时间:2007-11-07 Tag: 点击:
 
创建模块:
使用module关键字
 
module Sentence
  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()

上一页 1 2下一页
[收藏] [推荐] [评论] [打印] [关闭]
上一篇:扩展Ruby
下一篇:在Ajax设计程序时动态加载文本域和下拉框
最新评论共有 4 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册
栏目列表
热点关注
相关文章