易截截图软件、单文件、免安装、纯绿色、仅160KB

Ruby学习笔记四——模块


#一、模块定义及引用,模块就是一段代码,里面有一些方法放一起。
#定义模块用module...end 。模块与类非常相似,但是:
#A) 模块不可以有实例对象;
#B) 模块不可以有子类。
include Math
puts sqrt(91);
module Me
  def sqrt(a)
  puts a*a;
  return a*a;
end
PI=3.1415926
end
include Me
puts sqrt(10)
puts Math.sqrt(10);
puts Math::PI;
puts Me::PI;#变量引用与方法调用不同,用双冒号,而不是点号
#二、可变参数
def params(*num)
"This is text sqrt. "
puts num.size
puts num[1]
puts num.inspect
end
params(4,2,3)
#三、模块的第三个作用,实现类似于多重继承的功能,也称Mix-in
#我们有一个Student类,有着Person类的属性和方法,还会做数学题——求平方根。已经有了Me模块,只要Mix-in 在Student类里就可以了。
module Me
  def sqrt(num, rx=1, e=1e-10)
    num*=1.0
    (num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
  end
end
class Person
  def talk
    puts "I'm talking."
  end
end
class Student < Person
  include Me
end
aStudent=Student.new
aStudent.talk # I'm talking.
puts aStudent.sqrt(20.7,3.3) # 4.54972526643248
#通过“ < 父类名 ” ,一个子类可以得到父类的属性和方法;通过“ include模块名 ” ,一个子类可以得到某个模块的常量和方法。类不能被 include 。
#四、extend,混型的另一种情况
module Me
  def sqrt(num, rx=1, e=1e-10)
    num*=1.0
    (num - rx*rx).abs <e ? rx : sqrt(num, (num/rx + rx)/2, e)
  end
end
class Student
end
aStudent=Student.new
aStudent.extend(Me)
puts aStudent.sqrt(93.1, 25) # 9.64883412646315
#include 方法为一个类的所有对象包含某个模块; extend 方法为一个类的某个对象包含某个模块。
#五、require和load
#require,load用于包含文件;include,extend则用于包含模块。
#require加载文件一次,load加载文件多次。
#require加载文件时可以不加后缀名,load加载文件时必须加后缀名。
#require一般情况下用于加载库文件,而load用


相关文档:

rails on ruby exmaples depot

1.install ruby
    download from http://www.ruby-lang.org/en/news/2009/12/07/ruby-1-9-1-p376-is-released/
2.install rails
   ruby gem install rails --include-dependencies
3.install mysql
   download from http://sourceforge.net
   ruby gem install&nb ......

Ruby的装饰器模式实现

class Tree
def initialize
puts "Make a normal tree"
end
def decorate
puts "Make sure the tree won\'t fall"
end
end
class RedBalls < Tree
def initialize(tree)
@parent = tree;
end
def decorate
@parent.decorate
puts "Put on some red balls"
end
end ......

升级到snow leopard后ruby的问题

1. ruby已成为1.87 2. 必须先安装安装光盘里的新的xcode,在"optional"目录里 3. 可能需要重新安装macport http://trac.macports.org/wiki/Migration 4. 或者升级macport http://weblog.rubyonrails.org/2009/8/30/upgrading-to-snow-leopard $ sudo port selfupdate
$ sudo port sync
$ sudo port upgrade --force insta ......

交互式 Ruby Shell irb

irb 是从命令行运行的
irb 的命令行选项(摘自 Porgramming Ruby 第二版)
-f
禁止读取~/.irbrc Suppress reading ~/.irbrc.
-m
数学模式(支持分数和矩阵) Math mode (fraction and matrix support is available).
-d
设置#DEBUG为true(同ruby -d一样)  Set $DEBUG to true (same as ``ruby -d'').
-r lo ......

Ruby 一步步安装


http://www.gayathri-frenzy.com/technology/ruby-on-rails
I kept thinking for a while on what do I have next in the store
Here we go “Ruby on Rails”
Ruby on Rails, often shortened to Rails or RoR, is an open source web application framework for the Ruby Programming language.Ruby is a ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号