Project

General

Profile

Actions

Feature #18478

open

Module#constant_pairs

Added by johansenjaa (Joseph Johansen) almost 3 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:107066]

Description

Let's say I have a module like this:

module A
  B = 1

  class C
  end
end

I can find out its constants with constants:

A.constants # => [:B, :C]

But if I also want to get the values of the constants, the best way at the moment seems to be with Object#const_get (and perhaps not so performant too? By the looks of things it has a fair bit of logic in it)

A.constants.to_h { |c| [ c, A.const_get(c)] }

It would be great if there was an easier/more optimal way of doing this:

A.constant_pairs # => { B: 1, C: A::C }

It seems like others have been interested in similar functionality before too:

https://stackoverflow.com/questions/48386101/get-value-of-all-constants-defined-in-a-module
https://stackoverflow.com/questions/9848153/how-do-you-find-all-modules-and-classes-within-a-module-recursively
https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activesupport/test/core_ext/object/json_gem_encoding_test.rb#L23
https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activerecord/test/cases/arel/nodes/node_test.rb#L12
https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activesupport/test/broadcast_logger_test.rb#L18
https://github.com/rails/rails/blob/f95c0b7e96eb36bc3efc0c5beffbb9e84ea664e4/activesupport/test/json/encoding_test.rb#L30

No data to display

Actions

Also available in: Atom PDF

Like0