二、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
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