例如:
ABC = 'abc'
DEF = 'def'
XYZ = 'anything'
LIST_ALL = [ABC, DEF, XYZ]
如果我这样做
LIST_ALL.reject(&:blank?).join(', ') # => "abc, def, anything"
我要找的是得到常数名,而不是他们的价值 预期产出:
LIST_ALL.something() #=> "ABC, DEF, XYZ"
方法#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
错误:
(NameError) uninitialized constant ABC;
答案 0 :(得分:4)
CONSTANT = 'my constant value'
instance = Class.new
CONSTANT = instance
instance.name.to_s
=> "CONSTANT"
不幸的是,这会弄乱你的常数值,而这不是你想要的。
在任何情况下,我看到的解决方案是直接停止使用常量并使用哈希。就像:
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"
如果你仍然想要使用元编程,check this answer。
答案 1 :(得分:2)
将常量名称存储为字符串,当您想要检查常量值时,请使用`#constantize'...
ABC = 'abc'
DEF = 'def'
GHI = ''
XYZ = 'anything'
LIST_ALL = %w(ABC DEF GHI XYZ)
然后你可以......
LIST_ALL.reject{|c| c.constantize.blank?}.join(', ') # => "ABC, DEF, XYZ"
答案 2 :(得分:0)
课堂内的实施细节。
添加<classname>::<constant_name>
否则抛出(NameError)未初始化的常量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
注意:要使用constantize,Ruby on Rails是必备的。