Ruby学习笔记三——类
#一、定义一个类
class Person
def initialize(name,age=18)
@name=name;
@age=age;
@motherland="china";
end
def talk
puts "my name is "+@name+" and I am "+@age.to_s
if @motherland == "china"
puts "I am a Chinese."
else
puts "I am a foreigner."
end
end#talk结束
attr_writer:motherland
attr_writer:age
end#class结束
p1=Person.new("Zhangren",10);
p1.talk;
p1.motherland="abc";
p1.talk;
p1.age=20;
p1.talk;
#二、继承自一个类
class Student < Person
def talk
#super;#这会调用父类talk中的代码
puts "I am a student. my name is "+@name+", age is "+@age.to_s
end # talk方法结束
end # Student类结束
p3=Student.new("kaichuan",25); p3.talk
p4=Student.new("Ben"); p4.talk
#Ruby没有重载方法,因为参数没有类型,所以没法重载。有多态,不过不太明显,因为变量都没有类型,所以谈不上父类引用指向子类对象,都是统一的引用。
#三、变量动态性
# E5.3-1.rb
a=5
b="hh"
puts "a = #{a} #{b} #{a}"
puts "b = #{b}"
#四、重写
def talk (a,b=1)
puts "This is talk version 2."
end
def talk (a)
puts "This is talk version 1."
end
talk (2) # This is talk version 1.
#talk (2,7) # 报错,因为重写之后,只有后一个有用,没有重载。父子类中也是重写。
#五、Ruby的变量等标识名称区分太小写。全局变量用$引用,实例变量用@(也就是成员变量,因为不需要声明,都是直接用),类变量用@@(其实就相当于静态变量)
$a="\n a is a global value"
puts $a
class StudentClass
@@count=0
def initialize( name )
@name = name
@@count+=1
end
def talk
puts "I am #@name, This class have #@@count students."
end
end
p1=StudentClass.new("Student 1 ")
p2=StudentClass.new
相关文档:
ruby中自带实现观察者模式的类observer。可以利用它来实现观察者模式。
代码例子:
# -*- coding: GB2312 -*-
require 'observer'
# 观察者模式(ruby)的使用例子
# 被观察者P
class PObservable
include Observable
end
# 观察者A
class AObserver
# update方法名是必须的要有的
def update(arg)
puts "AO ......
照例可以先看端程序
class Person
def initialize( name,age=18 )
@name = name
@age = age
@motherland = "China"
end
def talk
puts "my name is "+@name+", age is "+@age.to_s
&n ......
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 ......
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 ......