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

前端 未结 4 1541
长情又很酷
长情又很酷 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 13:59

    Your sequence is equivalent to:

    c_names = Foo.constants #=> ["Bar"]
    cs = c_names.map { |c_name| Foo.__send__(:const_get, c_name) } #=> [Foo::Bar]
    cs.select{ |c| Class === c } #=> [Foo::Bar]
    

    You can consider Object#method as (roughly):

    class Object
      def method(m)
        lambda{ |*args| self.__send__(m, *args) }
      end
    end
    

    grep is described here http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-grep

    === for Class (which is subclass of Module) is described here http://ruby-doc.org/core-1.9.3/Module.html#method-i-3D-3D-3D

    UPDATE: And you need to grep because there can be other constants:

    module Foo
      PI = 3.14
      ...
    end
    

    and you probably don't need them.

提交回复
热议问题