Techioz Blog

Ruby 定数の前に「::」を付ける必要があるのはどのような場合ですか? (初期化されていない定数エラー)

概要

これとともに

class BaseClass
end

これとともに

module SomeModule
  class SomeClass < BaseClass
  end
end

これとともに

これとともに

解決策

これとともに

module SomeModule
  puts Module.nesting.inspect # the current module nesting is [SomeModule] 
end

これとともに

これとともに

module Bar
  def self.hello
    puts "Hello from the top level Bar"
  end
end

module Foo
  module Bar


    def self.hello
      puts "Hello from Foo::Bar"
    end
  end

  def self.test
     Bar.hello # the current module nesting is Foo.
     ::Bar.hello
  end
end 

Foo.test
# Will output:
# Hello from Foo::Bar
# Hello from the top level Bar

これとともに

これとともに