Tag: introspection

当内省模块类时,“#map(&proc)”成语如何工作?

提出成语 我发现了一个有趣但无法解释的替代方案 。 代码显然适用于REPL。 例如: module Foo class Bar def baz end end end Foo.constants.map(&Foo.method(:const_get)).grep(Class) => [Foo::Bar] 但是,我并不完全理解这里使用的习语。 特别是,我不理解使用&Foo ,它似乎是某种闭包,或者#grep的这种特定调用如何对结果进行操作。 解析成语 到目前为止,我已经能够解析其中的一些部分,但我并没有真正看到它们如何组合在一起。 以下是我认为我对示例代码的理解。 Foo.constants返回模块常量数组作为符号。 method(:const_get)使用Object#方法执行方法查找并返回闭包。 Foo.method(:const_get).call :Bar是一个闭包,它返回类中常量的限定路径。 &Foo似乎是某种特殊的lambda 。 文档说: 如果proc对象由&参数给出,&参数将保留技巧。 我不确定我是否完全明白在这个特定背景下这意味着什么。 为什么选择Proc? 什么“诡计”,为什么这里有必要? grep(Class)正在对#map方法的值进行操作,但其function并不明显。 为什么这个#map构造返回一个greppable Array而不是Enumerator? Foo.constants.map(&Foo.method(:const_get)).class => Array 如何为名为Class的类的grepping实际工作,为什么这里需要特定的构造? [Foo::Bar].grep Class => [Foo::Bar] 问题,重申 我真的很想完全理解这个成语。 任何人都可以在这里填补空白,并解释这些碎片是如何组合在一起的吗?

我如何在Ruby中反省内容?

例如,在Python中,如果我想获取对象的所有属性,我可以做这样的事情: >>> import sys >>> dir(sys) [‘__displayhook__’, ‘__doc__’, ‘__excepthook__’, ‘__name__’, ‘__package__’, ‘__stderr__’, ‘__stdin__’, ‘__stdout__’, ‘_clear_type_cache’, ‘_current_frames’, ‘_getframe’, ‘api_version’, ‘argv’, ‘builtin_module_names’, ‘byteorder’, ‘call_tracing’, ‘callstats’, ‘copyright’, ‘displayhook’, ‘dont_write_bytecode’, ‘exc_clear’, ‘exc_info’, ‘exc_type’, ‘excepthook’, ‘exec_prefix’, ‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘getcheckinterval’, ‘getdefaultencoding’, ‘getdlopenflags’, ‘getfilesystemencoding’, ‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘gettrace’, ‘hexversion’, ‘maxint’, ‘maxsize’, ‘maxunicode’, ‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’, ‘path_importer_cache’, ‘platform’, ‘prefix’, […]

有什么方法可以确定哪个对象叫做方法?

我希望Ruby的消息传递基础设施意味着可能有一些聪明的技巧。 如何确定调用对象 – 哪个对象称为我当前使用的方法?