4

我有一个如下所示的类:

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 范围内做一些愚蠢的事情。我目前正在测试此代码的机器上使用 Ruby 1.9.3p0。

4

3 回答 3

4

工作中:

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。所以删除Object,它会工作..

于 2013-08-29T22:08:09.817 回答
3

你可以使用 const 像:

Foo::MY_CONST
Foo::ANOTHER_CONST

您可以使用一组常量:

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
于 2013-08-29T22:09:01.747 回答
2

我建议通过 self 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
于 2017-11-07T15:35:10.203 回答