2013-08-29 66 views
2

的情况下我有一个类,如下所示:红宝石:访问类常数

class Foo 
    MY_CONST = "hello" 
    ANOTHER_CONST = "world" 

    def self.get_my_const 
    Object.const_get("ANOTHER_CONST") 
    end 
end 

class Bar < Foo 
    def do_something 
    avar = Foo.get_my_const # errors here 
    end 
end 

获得一个const_get uninitialized constant ANOTHER_CONST (NameError)

假设我只是在做一些愚蠢的在尽可能红宝石范围去。我正在测试此代码的机器上使用Ruby 1.9.3p0。

+3

您希望在'Foo'上调用'const_get',而不是在'Object'上调用'const_get'。 'Foo'继承自'Object',所以它会响应'const_get',但是你需要将消息发送给可以正确响应它的对象 - 在这种情况下是'Foo',因为这是对象const被定义。 –

+0

@ChrisHeald恰到好处!我可以把它放在我的答案中,就像你已经解释过的,或者让它自己评论一下? :) –

回答

3

现在的工作:

class Foo 
    MY_CONST = "hello" 
    ANOTHER_CONST = "world" 

    def self.get_my_const 
    const_get("ANOTHER_CONST") 
    end 
end 

class Bar < Foo 
    def do_something 
    avar = Foo.get_my_const 
    end 
end 

Bar.new.do_something # => "world" 

你的下面部分是不正确的:

def self.get_my_const 
    Object.const_get("ANOTHER_CONST") 
end 

里面的方法get_my_const,自我是Foo。所以删除Object,它会运行

2

您可以使用常量,如:

Foo::MY_CONST 
Foo::ANOTHER_CONST 

可以Gey中的常量数组:

Foo.constants 
Foo.constants.first 

与您的代码:

class Foo 
    MY_CONST = 'hello' 

    def self.get_my_const 
     Foo::MY_CONST 
    end 
end 


class Bar < Foo 
    def do_something 
     avar = Foo.get_my_const 
    end 
end 


x = Bar.new 
x.do_something 
+0

我需要从一个字符串动态获取const,因此为什么我使用'Object.const_get',所以我需要能够通过调用一个类实例方法来获取它。 – randombits

+0

那么只需使用'const_get const_name',因为那会在'self'上调用'const_get',这将是您在该范围内的'Foo'类。 –

+0

好吧,请把它放在OP的代码里,让我知道..这不回答OP的实际发帖.. –

0

我建议通过自我self.class.const_get("MY_CONST"),所以你总是得到正确的常数。

class Foo 
    MY_CONST = "hello" 
    ANOTHER_CONST = "world" 
end 

class Bar < Foo 
    MY_CONST = "hola" 

    def do_something 
    [self.class.const_get("MY_CONST"), self.class.const_get("ANOTHER_CONST")].join(' ') 
    end 
end 

Bar.new.do_something #=> hola world