问题描述
我发现了一个接受答案。该代码显然可以在REPL中使用。例如:
I found an interesting but unexplained alternative to an accepted answer. The code clearly works in the REPL. For example:
module Foo
class Bar
def baz
end
end
end
Foo.constants.map(&Foo.method(:const_get)).grep(Class)
=> [Foo::Bar]
但是,我不完全理解此处使用的惯用语。特别是,我不理解& Foo
的使用,这似乎是某种封闭,或者#grep的特定调用如何对结果进行操作。
However, I don't fully understand the idiom in use here. In particular, I don't understand the use of &Foo
, which seems to be some sort of closure, or how this specific invocation of #grep operates on the result.
到目前为止,我已经能够解析其中的点点滴滴,但是我没有真正看到它们如何组合在一起。这是我对示例代码的理解。
So far, I've been able to parse bits and pieces of this, but I'm not really seeing how it all fits together. Here's what I think I understand about the sample code.
-
Foo .constants
以符号形式返回模块常量数组。
Foo.constants
returns an array of module constants as symbols.
method(:const_get)
使用进行方法查找并返回闭包。
method(:const_get)
uses Object#method to perform a method lookup and return a closure.
Foo.method(:const_get).call:Bar
是一个闭包,它返回类中常量的限定路径。
Foo.method(:const_get).call :Bar
is a closure that returns a qualified path to a constant within the class.
& Foo
似乎是。文档说:
我也不确定我是否完全理解在特定情况下的含义。为什么要进行?
I'm not sure I fully understand what that means in this specific context, either. Why a Proc? What "tricks," and why are they necessary here?
grep(Class)
的作用是什么? Foo.constants.map {| c | Foo.const_get(c)}
。 grep
使用 ===
来选择元素,因此它将仅获取引用类的常量,而不获取其他值。可以通过在 Foo
中添加另一个常量来验证这一点,例如 Baz = 1
,将不会得到 grep
。
So in the end this is just a pointfree way of saying Foo.constants.map { |c| Foo.const_get(c) }
. grep
uses ===
to select elements, so it would only get constants that refer to classes, not other values. This can be verified by adding another constant to Foo
, e.g. Baz = 1
, which will not get grep
ped.
如果您还有其他问题,请将其添加为评论,我会尽力澄清。
If you have further questions please add them as comments and I'll try to clarify them.
这篇关于“ #map(& proc)”如何进行?内省模块类时可以使用成语吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!