Ruby:is_a? instance_of?在基本对象中
Ruby: is_a? and instance_of? in BasicObject
如何is_a? instance_of?方法与 BasicObject 的子类一起使用 ?
class My < BasicObject
DELEGATE = [:is_a?, :instance_of?]
def method_missing(name, *args, &blk)
superclass unless DELEGATE.include? name
::Kernel.send(name,*args, &blk)
end
end
my = My.new
my.is_a? BasicObject #=> true
my.is_a? My #=> false ???
my.instance_of? My #=> false ???
::Kernel.send(name,*args, &blk)
使用参数 args
和块 &blk
.[=27 在 class Kernel
上调用方法 name
=]
当你运行my.is_a? My
name
是:is_a?
,*args
是My
,&blk
是nil
。你真是运行宁Kernel.is_a? My
.
相反,如果您想为 BasicObject
重新实现 is_a?
,您可以走 class 的 ancestors
...
def is_a?(target)
# I don't know how to get the current class from an instance
# that isn't an Object, so I'm hard coding the class instead.
return ::My.ancestors.include?(target)
end
您可以从 Kernel
:
窃取 is_a?
class My < BasicObject
define_method(:is_a?, ::Kernel.method(:is_a?))
end
m = My.new
m.is_a?(My) #=> true
m.is_a?(BasicObject) #=> true
m.is_a?(Object) #=> false
如果您要构建自己的对象层次结构,您也可以定义自己的 Kernel
,例如:
module MyKernel
[:is_a?, :instance_of?, :class].each do |m|
define_method(m, ::Kernel.method(m))
end
end
class My < BasicObject
include ::MyKernel
end
如何is_a? instance_of?方法与 BasicObject 的子类一起使用 ?
class My < BasicObject
DELEGATE = [:is_a?, :instance_of?]
def method_missing(name, *args, &blk)
superclass unless DELEGATE.include? name
::Kernel.send(name,*args, &blk)
end
end
my = My.new
my.is_a? BasicObject #=> true
my.is_a? My #=> false ???
my.instance_of? My #=> false ???
::Kernel.send(name,*args, &blk)
使用参数 args
和块 &blk
.[=27 在 class Kernel
上调用方法 name
=]
当你运行my.is_a? My
name
是:is_a?
,*args
是My
,&blk
是nil
。你真是运行宁Kernel.is_a? My
.
相反,如果您想为 BasicObject
重新实现 is_a?
,您可以走 class 的 ancestors
...
def is_a?(target)
# I don't know how to get the current class from an instance
# that isn't an Object, so I'm hard coding the class instead.
return ::My.ancestors.include?(target)
end
您可以从 Kernel
:
is_a?
class My < BasicObject
define_method(:is_a?, ::Kernel.method(:is_a?))
end
m = My.new
m.is_a?(My) #=> true
m.is_a?(BasicObject) #=> true
m.is_a?(Object) #=> false
如果您要构建自己的对象层次结构,您也可以定义自己的 Kernel
,例如:
module MyKernel
[:is_a?, :instance_of?, :class].each do |m|
define_method(m, ::Kernel.method(m))
end
end
class My < BasicObject
include ::MyKernel
end