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

You can use const like:

Foo::MY_CONST
Foo::ANOTHER_CONST

You can gey a array of constants:

Foo.constants
Foo.constants.first

With your code:

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 に答える