From: "johansenjaa (Joseph Johansen)" <noreply@...>
Date: 2022-01-11T19:55:39+00:00
Subject: [ruby-core:107066] [Ruby master Feature#18478] Module#constant_pairs

Issue #18478 has been reported by johansenjaa (Joseph Johansen).

----------------------------------------
Feature #18478: Module#constant_pairs
https://bugs.ruby-lang.org/issues/18478

* Author: johansenjaa (Joseph Johansen)
* Status: Open
* Priority: Normal
----------------------------------------
Let's say I have a module like this:
```ruby
module A
  B = 1

  class C
  end
end
```

I can find out its constants with `constants`:
```ruby
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)

```ruby
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:

```ruby
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



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>