Ruby BasicObject methods

5

在学习 Ruby 的过程中,我发现 BasicObject 是 Class 的最高父类。当我尝试运行 BasicObject.methods 时,会列出以下方法:

[:method_missing, :singleton_method_added, :singleton_method_undefined, :singleton_method_removed, :new, :become_java!, :allocate, :superclass, :java_class, :class_variables, :<=, :public_instance_methods, :prepend, :class_variable_get, :public_constant, :singleton_class?, :instance_methods, :freeze, :instance_method, :const_defined?, :to_s, :constants, :ancestors, :private_instance_methods, :===, :included_modules, :==, :using, :class_eval, :const_get, :refine, :protected_instance_methods, :public_instance_method, :class_variable_defined?, :inspect, :name, :private_constant, :<, :hash, :>, :>=, :module_exec, :protected_method_defined?, :module_eval, :const_missing, :class_exec, :const_set, :private_method_defined?, :public_class_method, :autoload, :<=>, :include, :public_method_defined?, :autoload?, :class_variable_set, :include?, :remove_class_variable, :deprecate_constant, :private_class_method, :method_defined?, :include_class, :handle_different_imports, :java_kind_of?, :public_send, :frozen?, :protected_methods, :java_implements, :public_method, :java, :singleton_methods, :untaint, :javafx, :enum_for, :private_methods, :method, :instance_variables, :object_id, :extend, :itself, :instance_variable_set, :respond_to?, :java_name, :methods, :to_java, :java_package, :singleton_class, :public_methods, :to_enum, :display, :tainted?, :instance_variable_defined?, :untrusted?, :define_singleton_method, :!~, :nil?, :com, :instance_of?, :java_require, :javax, :java_signature, :tap, :java_annotation, :send, :trust, :instance_variable_get, :is_a?, :eql?, :java_field, :remove_instance_variable, :untrust, :class, :=~, :org, :taint, :kind_of?, :clone, :dup, :!, :equal?, :instance_exec, :__id__, :instance_eval, :__send__, :!=]

我还安装了Jruby,所以有一些额外的方法。

但是当我调用BasicObject.methods(false)(false参数用于显示同一类本身的方法)时,我得到了:

=> [:method_missing, :singleton_method_added, :singleton_method_undefined, :singleton_method_removed]

我有一个问题,理想情况下,带有false参数的class.methods应该只返回它自己的方法,而BasicObject.superclass应该返回nil。还有其他层次结构吗?这些方法是从哪里来的。

我正在学习Ruby,如果我有所遗漏,请见谅。


1
我认为这些方法是特定于JRuby的,可能会在BasicObject类上添加一些方法。我有: BasicObject.methods(false) => [] - Poilon
2个回答

1
你并不是在询问 BasicObject 上定义的实例方法,那应该使用 BasicObject.instance_methods。你所问的是,你可以调用哪些方法在 BasicObject 上。嗯,BasicObject 就像任何其他对象一样,因此您可以调用其类中定义的任何方法(在这种情况下是 Class),或者其类的超类中定义的方法(在这种情况下是 ModuleObjectKernelBasicObject)。

0

这些方法确实是在BasicObject上定义的,尽管它们大多只是空定义(method_missing实际上做了一些工作)。请查看source

我不能确定原因,但评论中可能有一些提示:

已经采取了一些措施,使实现尽可能单态化,以便Java Hotspot引擎可以提高其性能。这就是为什么该类中可能会出现几个看起来奇怪的模式的原因。

这些方法都是重新定义用于元编程目的的常见钩子。通过在BasicObject上定义它们,可能可以通过简化继承链来实现更快的方法解析。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接