- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在学习一些元编程,但一直在努力寻找一种方法。假设我有以下类(class):
class MyClass
def self.my_method
end
def your_method
end
end
使用以下代码我可以在对象空间中搜索每个方法:
type = Class
name = /^my_method$/
result = ObjectSpace.each_object(type).select do |o|
o.instance_methods(false).grep(name).size > 0 || o.methods.grep(name).size > 0
end
p result
它发现它显示了以下输出:
[MyClass]
由于搜索器代码还会搜索实例方法,因此在查找 your_method 时会显示相同的输出。
即使我向对象添加单例方法:
mc = MyClass.new
def mc.our_method
end
像这样改变搜索器:
type = Object
name = /^our_method$/
result = ObjectSpace.each_object(type).select do |o|
o.methods.grep(name).size > 0
end
p result
它也找到了它:
[#<MyClass:0x8f86760>]
问题是,如何找到定义在顶级对象中的方法?这个方法:
def hidden
end
另外,定义这样的方法时,当前类是哪个?
最佳答案
Which is the current class when defining a method like this?
我们可以通过检查这个顶级范围内的 self
轻松找出我们所在的对象:
self #=> main
self.class #=> Object
所以我们不是在一个类中,而是在一个被称为“main”的对象实例中。
How do I find a method defined in the top level object?
这就是它变得有趣的地方。 Ruby 中的顶级作用域对象表现特殊,但发现此处定义的方法所在的位置相对容易:
def foo; :bar; end
method(:foo).owner #=> Object
Object.new.foo #=> NoMethodError: private method `foo' called
Object.new.send(:foo) #=> :bar
所以在顶层定义的方法是对象的(私有(private)*)实例方法。你的“搜索者”找不到它的原因是因为这些方法是私有(private)的,methods
和 instance_methods
都不包含私有(private)方法,相反你需要 private_methods
和 private_instance_methods
:
Object.instance_methods.include?(:foo) #=> false
Object.private_instance_methods.include?(:foo) #=> true
* 请注意,Pry(至少 v0.10.1)对此进行了更改,使其 REPL 中的顶层定义方法公开。
关于ruby - 顶层定义的方法在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242692/
我正在开发一个需要多个窗口的程序,第一个出现的是登录窗口,我使用了 Toplevel 小部件以使其他窗口成为其子窗口,但这段代码一直显示两个窗口而不是一个。 from Tkinter import F
我不知道一般如何实现这一点,但为了清楚起见,我会特别询问一个实例: Sexplib 对我来说看起来很有趣。我想玩弄它。我已经下载了它,安装得很好(反正我很确定)等等。我想在顶层使用“with sexp
我在 makefile 中设置一个变量,如下所示: SOMEVAR = foo 此 makefile 稍后包含一些其他 makefile,在其中进行实际的程序构建: include generic/M
from tkinter import* import tkinter as tk def topLevel(): top=Toplevel() top.title("Listbox
我想查看乘法函数 (*) 的类型,因此我将其输入 OCaml 顶层。 # (*) 然而,顶层回应: (*);; 1: this is the start of a comment. 然后消耗我输入的任
我喜欢Try Ocaml的顶层行为:;; 在我按下 Enter 时隐式添加,并且我能够使用 Shift-Enter 进行多行编辑。 是否有可能在标准顶层或 utop 中获得相同的功能? 最佳答案 目前
我想知道,在 Ocaml 中,是否有部分输入信息。对于无法编译的程序,可以通过顶层/编译器的某些现有功能来绘制吗?让我解释。 在 Ocaml 中,众所周知,可以通过 -annot 文件检索推断类型。但
当我将分层 SVG 文件加载到 Illustrator 中时,所有图层都按其应有的方式工作,但它们始终位于新图层下;我没有指定“第 1 层”。 如何创建一个 SVG,使我的顶层最终也成为 Illust
我遇到了让我的 TreeView 填充已创建的顶层窗口的挑战,已尝试 fill=“x”和 fill=“both”,但没有得到结果。有任何建议这样做。 from tkinter import ttk i
标签在 div 中
我有以下布局: target target not target 我的问题是,如何定位所有顶级 标签(参见 target )使用 .fin
大家好,我有一个 div.mapFullscreenContainer #mapFullscreenContainer { position:fixed; top:0; lef
我有一个以编程方式创建的标签栏 Controller ,名为 TPastJourneyTabbar。当我单击 TableView 并调用 didSelectRowAtIndexPath: 时,我的选项
我是一名优秀的程序员,十分优秀!