ruby 基础教程1-8-1

1.":class, instance_of?, :is_a?"都是Object类的方法,每个对象都可以调用

2.":class"方法用户获取对象归属类的名称

3.":instance_of?"方法用于判断对象是否为某个类的实例

4.":is_a?"方法用于判断,对象在继承层次上是否归属于某一个类

5.BasicObject是Object类的父类,Object类是所有不直接继承自BasicObject类的父类。

6.所有类默认继承自Object类,要直接继承BasicObject类,需要显示写明

7.调用一个类的new方法,其initialize方法就会被调用。

8.类名首字母必须大写

9.存取器 attr_reader,attr_write,attr_accessor

10.self表示对象本身

11.类方法定义语法

a.class << 类名 ~ end

b.class <<self ~ end

c. def 类名.方法名 ~end

12.类变量"@@name",类方法定义 def classname.funcname ~ end

13.访问控制 public,private,protected

public :name1,:name2,:name3

或者 public

def f1 ~ end

def f2 ~ end

def f3 ~ end

默认情况下方法都被定义为public,但是initialeze方法会默认定义为private

14.类外部可读,内部才可写的变量定义方法

attr_accessor :x,:y

protected :x=,:y=

15.可以在已有类上进行扩展

class 已有类名

def newMethod

end

end

16.在子类调用同名父类 super(paramlist)

17.instance_methods 打印类的实例方法

18.alias 别名 原名

alias :别名 :原名 定义别名

19 undef可以删除父类的方法

20 定义实例方法

a=A.new

def a.func

end

a.func

class TestClassMethod

@@cnt=0

def TestClassMethod.count

@@cnt+=1

end

end

puts TestClassMethod.count

puts TestClassMethod.count

class A

def func1

puts "A#func1 is Called"

end

end

class B < A

@@count=0

def func2

puts "B#func2 is Called"

end

end

class << B

def incCnt

puts "hello"

end

end

b = B.new

puts b.instance_of?(A) =>false #直属查找

puts b.is_a?(B) =>true

puts b.is_a?(A) =>true #继承层次上查找

str1="luocaimin"

str2="luocaimin"

def str2.hello

puts "Hello #{self}"

end

p str2.hello

p str1.hello

class C1

def hello

puts "hello"

end

end

class C2<C1

alias old_hello hello #把父类的同名方法定义为别名

def hello

puts "#{old_hello},again" #使用别名

end

end

c = C2.new

c.old_hello

c.hello

class String

def count_word

self.split(/\s+/)

end

end

str = "Today is wonderful day"

arr = str.count_word

puts arr.size

class RingArray < Array

def [](i)

index=i%size

super(index)

end

end

ra = RingArray[1,2,3,4,5,6,7,8,9]

p ra[11]

p ra[21]

p Object.instance_methods

p BasicObject.instance_method