2013-08-29 69 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