11

I want to get the values of all the constants defined in a module:

module Letters
  A = 'apple'.freeze
  B = 'boy'.freeze
end

constants gave me the name of the constants:

Letters.constants(false)
#=> [:A, :B]

How do I get an array of their values, i.e. ["apple", "boy"]?

Sahil Rally
  • 541
  • 3
  • 15

1 Answers1

16

In order to do this use map

Letters.constants(false).map &Letters.method(:const_get)

this will return ["a","b"]

Second way :

Letters.constants(false).map { |c| Letters.const_get c }

Thanks @mudasobwa and Sagar Pandya for their answer.

Sahil Rally
  • 541
  • 3
  • 15
  • 3
    Some may prefer `Letters.constants(false).map { |c| Letters.const_get c }` – Sagar Pandya Jan 22 '18 at 17:03
  • 1
    You edited your answer to replace what you had initially with @mudasobwa's comment (*verbatim!*). Considering that mudsie chose not to submit an answer, there's nothing wrong with that (it's a good answer, so we need to see it), but don't you think you should have attributed it to him? – Cary Swoveland Jan 23 '18 at 05:00
  • @CarySwoveland Absolutely ! – Sahil Rally Jan 23 '18 at 08:23