二、Kernel 和 Object
1、引入了BasicObject对象,作为一个顶级的空白状态对象:
BasicObject.instance_methods
#
=> [:==,:equal?,:"!",:"!=",:__send__]
Object.ancestors
#
=> [Object, Kernel, BasicObject]
引入这个对象对于Ruby对象体系带来的影响我还不清楚。
2、instance_exec方法,允许传递参数、self到一个block并执行之,也就是说为特定的instance执行block。
def
magic(obj)
def
obj.foo(
&
block) instance_exec(self, a, b,
&
block) end end o
=
Struct.new(:a,:b).new(
1
,
2
) magic(o) puts o.foo{
|
myself,x,y
|
puts myself.inspect;x
+
y }
更多例子:
o
=
Struct.new(:val).new(
1
) o.instance_exec(
1
){
|
arg
|
val
+
arg }
=>
2
在Ruby 1.8中实现这个方法:
class
Object module InstanceExecHelper; end include InstanceExecHelper
def
instance_exec(
*
args,
&
block)
#
!> method redefined; discarding old instance_exec
mname
=
"
__instance_exec_#{Thread.current.object_id.abs}_#{object_id.abs}
"
InstanceExecHelper.module_eval{ define_method(mname,
&
block) } begin ret
=
send(mname,
*
args) ensure InstanceExecHelper.module_eval{ undef_method(mname) } rescue nil end ret end end
3、Kernel的require方法载入的文件将以完整路径存储在变量$"中,等价于:
$
"
<< File.expand_path(loaded_file)
通过在irb中观察$"变量即可看出差别。
4、Object#tap方法,将对象传入block并返回自身,用于链式调用:
"
hello
"
.tap{
|
a
|
a.reverse!}[0]
#
=> "o"
"
F
"
.tap{
|
x
|
x.upcase!}[0]
#
=> "F" (注意到"F".upcase!返回的是nil)
5、Kernel#instance_variable_defined?方法:
a
=
"
foo
"
a.instance_variable_defined? :@a
#
=> false
a.instance_variable_set(:@a,
1
) a.instance_variable_defined? :@a
#
=> true
6、Object#=~
匹配失败的时候返回nil而不是false
1
=~
1
#
=> nil
7、Kernel#define_singleton_method 方法,
a
=
""
a.define_singleton_method(:foo){
|
x
|
x
+
1
} a.send(:foo,
2
)
=>
3
a.foo(
2
)
=>
3
8、Kernel#singleton_methods, Kernel#methods,返回的是将是方法名symbol组成的数组,过去是方法名的字符串数组。
文章转自庄周梦蝶 ,原文发布时间 2008-10-01
相关资源:敏捷开发V1.0.pptx