Home How to convert Array of Constants into String with the constant names and not its assigned values
Reply: 3

How to convert Array of Constants into String with the constant names and not its assigned values

Aayush Kumar Singha
1#
Aayush Kumar Singha Published in 2018-02-13 20:06:42Z

For example:

ABC = 'abc'
DEF = 'def'
XYZ = 'anything'
LIST_ALL = [ABC, DEF, XYZ]

If I do

LIST_ALL.reject(&:blank?).join(', ') # => "abc, def, anything"

What I am looking for is to get the constant names, not their values Expected output:

LIST_ALL.something() #=> "ABC, DEF, XYZ"

Approach #1:

class X
  ABC = "abc"
  DEF = "def"
  GHI = ""
  XYZ = "anything"
  LIST_ALL = %w(ABC DEF GHI XYZ)

  def self.something()
     puts LIST_ALL.reject{|c| c.constantize.blank?}.join(', ')
     # puts LIST_ALL[0].constantize
  end
end

Error:

(NameError)  uninitialized constant ABC;
SteveTurczyn
2#
SteveTurczyn Reply to 2018-02-14 13:37:21Z

Store the constant names as strings, when you want to check the constant value use `#constantize'...

ABC = 'abc'
DEF = 'def'
GHI = ''
XYZ = 'anything'
LIST_ALL = %w(ABC DEF GHI XYZ)

Then you can do...

LIST_ALL.reject{|c| c.constantize.blank?}.join(', ') # => "ABC, DEF, XYZ"
vnbrs
3#
vnbrs Reply to 2018-02-14 13:01:10Z

Ruby has no explicit hook for instance naming, as I can see. However, classes does.

CONSTANT = 'my constant value'
instance = Class.new
CONSTANT = instance
instance.name.to_s
=> "CONSTANT"

Unfortunately, this will mess with your constant value, and that's not what you want.

In any case, a solution I see is to stop using constants directly and use a hash. Just like:

MY_HASH  = { 'ABC' => 'abc', 'DEF' => 'def' }
puts "constant names are #{MY_HASH.keys.join(', ')}"
=> "constant names are ABC, DEF"

puts "constant values are #{MY_HASH.values.join(', ')}"
=> "constant values are abc, def"

If you still wanna mess with metaprogramming, check this answer.

Aayush Kumar Singha
4#
Aayush Kumar Singha Reply to 2018-02-16 22:37:39Z

Implementation details inside a class.
Add <classname>::<constant_name> otherwise throws (NameError) uninitialized Constant ABC:

class X
  ABC = "123"
  DEF = "456"
  LIST_ALL = %w(X::ABC X::DEF)

  def something()
    puts LIST_ALL.reject{|c| c.constantize.blank?}.join(', ') # output: X::ABC, X::DEF
    puts LIST_ALL[0].constantize # output: 123
  end
end

Note: to use constantize, Ruby on Rails is pre-requisite.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300375 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO