Get value of all constants defined in a module

喜欢而已 提交于 2021-02-08 13:28:09

问题


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"]?


回答1:


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.



来源:https://stackoverflow.com/questions/48386101/get-value-of-all-constants-defined-in-a-module

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!