Advanced Rails -- Ruby 基本技术(2) -- Ruby 基础1

[b]Ruby 基础[/b]

[i]类和方法[/i]

类和方法是Ruby里面向对象的基础。类便利了关系的包装和分解。模块可以用来做mixins—用一替代多继承来把一堆功能添加到类里面已增加类的行为。模块的另一个作用就是把类分到命名空间(namespace) 里。

在Ruby里,类的名字是一个常量。这就是为什么Ruby要求类的名字必须以大写字母开头的原因。这些常量会记值在类的对象里,这个对象就是类Class的一个对象。这个和Class对象是不同的,Class是一个类。“class object”表示一个类。“Class object”是一个类,名字是Class,它是所有类对象的superclass。

类Class继承与Module,所有的类因此也是一个模块。但是Classes不能做mixins,也不能扩展一个对象。

[i]方法的查找[/i]

每一Ruby的对象(除了Fixnums,symbols,true,false,nil)都有下面这些字段的集合:
klass
指向这个对象的类对象
iv_tbl
是储存这个对象实例变量的Hash表
flags
状态信息
m_tbl
方法表
super
指向父类的指针


[i]规则[/i]

1. Ruby跟随接受者kclass的指针,搜索这个类m_tbl
2. 如果没有找到,Ruby跟踪类对象的super的指针,继续搜索m_tbl
3. Ruby用这种方式查找直到找到这个方法或者到了类链的顶部
4. 如果没有找到,Ruby在最初接受者调用method_missing。然后用同样的方法开始查找method_missing。
单类

单类也被称为元类,它允许一个对象的行为区别于同一个类的其他对象


class A
end

objA = A.new
objB = A.new
objA.to_s # => "#<A:0x1cd0a0>"
objB.to_s # => "#<A:0x1c4e28>"

class <<objA # Open the singleton class of objA
def to_s; "Object A"; end
end

objA.to_s # => "Object A"
objB.to_s # => "#<A:0x1c4e28>"


单类会被标示为一个虚拟类,这个类在Ruby里一般看不到,除非特意去做。当访问objA的类的时候,会利用klass和super指针一层一层的去查找,直到找到第一个非虚类。这也说明了,一个对象的klass不一定指向它的类对象。

[i]Singleton classes of class objects[/i]

方法查找最基本的规则就是Ruby根据一个对象的klass指针搜索方法;然后Ruby在跟寻super指针一级一级的向上查找方法直到继承链的最顶端。

类也是对象。类也可以有单类(越来越难说明白了,呵呵,直接copy code了)



class A
end


class A; end
# from Module#to_s
A.to_s # => "A"

class Class
def to_s; "Class#to_s"; end
end

A.to_s # => "Class#to_s"


class A; end
class B; end

class <<A
def to_s; "Class A"; end
end

A.to_s # => "Class A"
B.to_s # => "B"


class method(类方法)定义的方式:

class A
def A.class_method_one; "Class method"; end

def self.class_method_two; "Also a class method"; end

class <<A
def class_method_three; "Still a class method";
end
end

class <<self
def class_method_four; "Yet another class method"; end
end
end

def A.class_method_five
"This works outside of the class definition"
end

class <<A
def A.class_method_six
"You can open the metaclass outside of the class definition"
end
end

# Print the result of calling each method in turn
%w(one two three four five six).each do |number|
puts A.send(:"class_method_#{number}")
end

# >> Class method
# >> Also a class method
# >> Still a class method
# >> Yet another class method
# >> This works outside of the class definition
# >> You can open the metaclass outside of the class definition



这也讲述了在一个单类的定义里——和其他类的定义——self表示的是这个定义类对象。

方法丢失
总结一下,method_missing非常的简单。当整个方法查找的过程失败后, 就会用同样的方法查找method_missing。当method_missing找到后,它会用和最初的方法同样的参数,并且在前面加上自出的方法名以调用。任何的代码块都会通过。

默认的method_missing函数在Object(rb_method_missing) 触发一个异常。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值