Ruby如何访问类中的常量?
- 内容介绍
- 文章标签
- 相关推荐
本文共计232个文字,预计阅读时间需要1分钟。
我有一段类似伪原创的代码如下:
pythonclass Foo: MY_CONST=hello ANOTHER_CONST=world def get_my_const(self): return Object.const_get(ANOTHER_CONST) end
class Bar: Foo.get_my_const()end
简化修改后的内容:
pythonclass Foo: MY_CONST=hello ANOTHER_CONST=world def get_my_const(self): return getattr(Object, ANOTHER_CONST) end
class Bar: Foo.get_my_const()end
我有一个类似于以下的类: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未初始化的常量ANOTHER_CONST(NameError)
假设我只是在Ruby范围内做一些愚蠢的事情.我正在我正在测试此代码的机器上使用Ruby 1.9.3p0.
工作中: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方法中,self是Foo.所以删除对象,它会工作..
本文共计232个文字,预计阅读时间需要1分钟。
我有一段类似伪原创的代码如下:
pythonclass Foo: MY_CONST=hello ANOTHER_CONST=world def get_my_const(self): return Object.const_get(ANOTHER_CONST) end
class Bar: Foo.get_my_const()end
简化修改后的内容:
pythonclass Foo: MY_CONST=hello ANOTHER_CONST=world def get_my_const(self): return getattr(Object, ANOTHER_CONST) end
class Bar: Foo.get_my_const()end
我有一个类似于以下的类: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未初始化的常量ANOTHER_CONST(NameError)
假设我只是在Ruby范围内做一些愚蠢的事情.我正在我正在测试此代码的机器上使用Ruby 1.9.3p0.
工作中: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方法中,self是Foo.所以删除对象,它会工作..

