Ruby 1.9概要(2)Kernel和Object
程序员文章站
2022-03-11 09:37:46
...
二、Kernel 和 Object
1、引入了BasicObject对象,作为一个*的空白状态对象:
<!---->BasicObject.instance_methods
#
=> [:==,:equal?,:"!",:"!=",:__send__]
Object.ancestors # => [Object, Kernel, BasicObject]
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 }
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
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
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)
" 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
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
a.define_singleton_method(:foo){ | x | x + 1 }
a.send(:foo, 2 ) => 3
a.foo( 2 ) => 3
8、Kernel#singleton_methods, Kernel#methods,返回的是将是方法名symbol组成的数组,过去是方法名的字符串数组。
上一篇: 请教PHP面向对象设计与数据可访问的设计
下一篇: 机器人判断人是否接近