How does the “#map(&proc)” idiom work when introspecting module classes?

前端 未结 4 1523
长情又很酷
长情又很酷 2021-02-13 13:29

Presenting the Idiom

I found an interesting but unexplained alternative to an accepted answer. The code clearly works in the REPL. For example:

module          


        
4条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 14:14

    &Foo.method(:const_get) is the method const_get of the Foo object. Here's another example:

    m = 1.method(:+)
    #=> #
    m.call(1)
    #=> 2
    (1..3).map(&m)
    #=> [2, 3, 4]
    

    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 grepped.

    If you have further questions please add them as comments and I'll try to clarify them.

提交回复
热议问题